标签: spring-test

spring @sqlgroup有多个数据源

我试图在我的单元测试中使用@sql和@sqlgroup但我希望这个注释使用不同于默认数据源的不同名称的数据源.

你怎么能实现这个目标?

spring-test

2
推荐指数
1
解决办法
2739
查看次数

获取 MockMvc perform() 方法的错误

我正在创建一个 Spring MVC 控制器测试。编译器以粗体显示以下方法的错误。我的代码中是否缺少一些库或其他东西?有什么建议?

我正在使用以下依赖项:

  <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
Run Code Online (Sandbox Code Playgroud)
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.zerosolutions.view.form.LoginCredentials;

@RunWith(value=SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:dispatcher-servlet.xml")
public class TestingFrontController {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void getLoginSignupPage() throws Exception{
        this.mockMvc.perform(**get**("/"))
        .andExpect(status().isOk()) …
Run Code Online (Sandbox Code Playgroud)

java spring spring-test mockmvc

2
推荐指数
1
解决办法
4382
查看次数

Spring Test + Mockito.mock - Spring 失败,因为它尝试加载模拟 bean @Autowired 依赖项

我无法找出以下简单场景失败的原因:我有一个带有过滤器的 Spring 应用程序,该过滤器从应用程序上下文加载 Spring bean:

public class MyFilter implements Filter{

    private IPermissionService permissionService;

    public void init(FilterConfig filterConfig) throws ServletException {
        WebApplicationContext ac = null;
        try{
            ac = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
            permissionService = ac.getBean(PermissionServiceImpl.class);
Run Code Online (Sandbox Code Playgroud)

PermissionServiceImpl 有一个 @Autowired 属性 dataSource 所以在我的 TestNG 测试中,我在 Spring applicationContext 中模拟它:

@Configuration
public class MyFilterSpringTestConfig{

    @Bean
    public IPermissionService permissionService(){
        return Mockito.mock(PermissionServiceImpl.class);
    }
Run Code Online (Sandbox Code Playgroud)

我的测试:

@Test
@WebAppConfiguration
@ContextConfiguration(classes=MyFilterSpringTestConfig.class)
public class MyFilterSpringTest extends BaseSpringFilterTest{

   ...
Run Code Online (Sandbox Code Playgroud)

问题是在 Spring 初始化时,我收到一个异常,抱怨 PermissionServiceImpl 的 dataSource 依赖项不满足。既然我用模拟包装了它,为什么它仍然失败?我怎么能修好呢?

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found …
Run Code Online (Sandbox Code Playgroud)

testng spring spring-test mockito

2
推荐指数
1
解决办法
2690
查看次数

如何在Spring MVC应用程序中测试Aspect

我有一个Spring MVC应用程序,在其中我使用Aspect来捕获所有控制器方法中的异常

@Component
@Aspect
public class ControllerExceptionAspect {

    private Logger logger;

    public ControllerExceptionAspect() {
       logger = Logger.getLogger(ControllerExceptionAspect.class);
    }

    public ControllerExceptionAspect(Logger logger) {
       this.logger = logger;
    }

    // Catching all exceptions from all methods in all controllers classes

    @AfterThrowing(pointcut = "execution(* com.my.package..controller..*(..))", throwing = "exception")
    public void afterThrowingAdvice(Exception exception) {
       logger.error("CONTROLLER ASPECT: EXCEPTION IN METHOD -> " +    
       exception.getClass());
    }
}
Run Code Online (Sandbox Code Playgroud)

Aspect可以正常工作,但是很遗憾,我无法对其进行测试。我尝试了很多次,但是在Controller中模拟异常后却无法获取如何捕获Aspect方法的信息

@SuppressWarnings("ALL")
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
        @ContextConfiguration(classes = RootConfig.class),
        @ContextConfiguration(classes = WebConfig.class)
})
public class ControllerExceptionAspectTest {

    @Autowired
    ApplicationContext applicationContext;

    @Test …
Run Code Online (Sandbox Code Playgroud)

java aspectj spring-mvc spring-test mockito

2
推荐指数
2
解决办法
4827
查看次数

系统属性 -Dspring.profiles.active 在 gradle 构建中的 Spring Boot 测试配置中不可用

我有一个 Spring Boot gradle 应用程序。当我运行 gradle 构建时,我想在不同的环境中运行。

例如:./gradlew clean build -Dapp.env=QA1。在测试代​​码中,我想检查此属性并相应地收集测试数据。我观察到的是该属性 (app.env) 不可用。

由于测试会检查系统属性,因此构建应该会失败。但构建成功。我也没有在控制台中看到 println 语句。

如果你想克隆回购:

git 克隆https://SpringDevSeattle@bitbucket.org/SpringDevSeattle/gs-rest-service.git

这是我的测试代码:

src/test/java/hello/GreetingControllerTests.java

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})
@WebAppConfiguration
public class GreetingControllerTests {


    @Autowired
    TestEnv testEnv;

    @Autowired
    Status status;

    private String env;

    @Before
    public void init(){
        System.out.println(status.getName());
        env=testEnv.getEnv();
    }

    @Test
    public void should_fail(){
        if (env.equalsIgnoreCase("DEV")){
            assertThat(false).isFalse();
        }
        if (env.equalsIgnoreCase("QA1")){
            System.out.println("failing the test");
            fail();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

src/test/java/hello/TestConfig.java

@Configuration
public class TestConfig {


    @Bean
    public TestEnv testEnv(){
        Properties properties = …
Run Code Online (Sandbox Code Playgroud)

spring spring-test gradle spring-boot

2
推荐指数
1
解决办法
1254
查看次数

为什么 Spring Boot 中有不同类型的集成测试

有人知道为什么 Spring Boot Guide 包含两种不同类型的集成测试吗?(https://github.com/spring-guides/gs-spring-boot#add-unit-tests

一个与 TestRestTemplate 和一个与 MockMvc 依赖?在每个测试类型中,spring boot 引导测试环境。那么这种分离的原因是什么呢?

testing spring spring-test resttemplate spring-boot

2
推荐指数
1
解决办法
555
查看次数

如何使kotlintest与Spring一起使用?

我正在尝试将kotlintest与Spring一起使用(不是Spring Boot,只是标准的spring-test)。我发现很难做到。关于我在做什么错的任何指示?我也是Kotlin的新手,所以我很可能做得不好。

到目前为止,这是我尝试过的:

import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.BehaviorSpec

import org.junit.ClassRule
import org.junit.Rule

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.rules.SpringClassRule
import org.springframework.test.context.junit4.rules.SpringMethodRule

open class SomeBean {
  open fun sayHello() = "Hello"
}

@Configuration
open class TestConfig {
  @Bean
  open fun someBean(): SomeBean = SomeBean()
}

@ContextConfiguration(classes = arrayOf(TestConfig::class))
open class MyTests(var someBean: SomeBean) : BehaviorSpec() {
  @Rule
  @JvmField
  val springMethodRule: SpringMethodRule = SpringMethodRule()

  companion object {
    @ClassRule
    @JvmField
    val SPRING_CLASS_RULE: SpringClassRule = SpringClassRule()
  }

  init {
    given("A test") {
      `when`("When my …
Run Code Online (Sandbox Code Playgroud)

spring-test kotlin kotlintest

2
推荐指数
2
解决办法
2405
查看次数

如何测试Spring @Conditional Bean

我有一个@Conditional bean-

@RestController("/user")
@ConditionalOnProperty(prefix = "user-controller", name = "enabled", havingValue = "true")
public void UserController {

@GetMapping
public String greetings() {
  return "Hello User";
}

}
Run Code Online (Sandbox Code Playgroud)

它可以启用或禁用。我想创建一个涵盖两个用例的测试。我怎样才能做到这一点?我只有一个application.properties文件:

user-controller.enabled=true
Run Code Online (Sandbox Code Playgroud)

我可以将属性注入bean并添加一个setter来通过代码进行管理,但是这种解决方案并不完美:

@RestController("/user")
@ConditionalOnProperty(prefix = "user-controller", name = "enabled", havingValue = "true")
public void UserController {

@Value("${user-controller.enabled}")
private boolean enabled;

public void setEnabled(boolean enabled) {
 this.enabled = enabled;
}

@GetMapping
public String greetings() {
  return enabled ? "Hello User" : "Endpoint is disabled";
}

}
Run Code Online (Sandbox Code Playgroud)

像这样

spring spring-test spring-boot

2
推荐指数
2
解决办法
2571
查看次数

带有控制器建议的 Spring 模拟 MVC 单元测试

我正在尝试测试我的控制器建议异常处理。我已将我的控制器建议注册到我的 mockmvc:

mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .setControllerAdvice(new ExceptionHandlingControllerAdvice())
            .build();
Run Code Online (Sandbox Code Playgroud)

我可以在控制台中看到测试正在选择异常处理方法:

org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver Detected @ExceptionHandler methods in com.myapp...ExceptionHandlingControllerAdvice
Run Code Online (Sandbox Code Playgroud)

ExceptionHandlingControllerAdvice 类有一个处理安全异常的方法:

@ExceptionHandler(SecurityException.class)
Run Code Online (Sandbox Code Playgroud)

当我的单元测试抛出 SecurityException 时,测试失败并显示堆栈跟踪,而不是调用控制器建议中的处理程序方法。

我做错了什么吗?

java spring unit-testing spring-mvc spring-test

2
推荐指数
1
解决办法
3392
查看次数

如何使用自定义@Rule正确配置@RunWith(Parameterized.class)+ SpringClassRule + SpringMethodRule?

我正在使用Spring Framework4.3.x和JUnit4,我有以下结构

@Transactional
@WebAppConfiguration
@RunWith(Parameterized.class)
@ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
@TestExecutionListeners(listeners={LoggingTestExecutionListener.class}, mergeMode=MergeMode.MERGE_WITH_DEFAULTS)
public class CompleteTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();
Run Code Online (Sandbox Code Playgroud)

因此组合:

  • @RunWith(Parameterized.class)+ SpringClassRule+SpringMethodRule

工作如何预期.

TestRule通过ExternalResource以下方式创建了一个自定义:

@Component
public class CompleteRule extends ExternalResource {

    private static final Logger logger = LoggerFactory.getLogger(CompleteRule.class.getSimpleName());

    private final WebApplicationContext webApplicationContext;

    private final Environment environment;

    private MockMvc mockMvc;

    public CompleteRule(WebApplicationContext webApplicationContext, Environment environment) {
        this.webApplicationContext = webApplicationContext; …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-test junit5

2
推荐指数
1
解决办法
694
查看次数