spring-boot - 有没有办法在 WebMvcTest 中包含一个 Spring 组件

标签 spring-boot spring-boot-test spring-web spring-test-mvc spring-mvc-test

给定生产代码类:

@RestController
@RequiredArgsConstructor
public class MyController {

    private final MyValidator validator;

    // annotations relating to request mapping excluded for brevity 
    public void test(@Valid @RequestBody final MyParams params) {
        // do stuff
    }

    @InitBinder
    @SuppressWarnings("unused")
    protected void initBinder(final WebDataBinder binder) {
        binder.setValidator(validator);
    }
}

@Component
@RequiredArgsConstructor
public class MyValidator implements Validator {

    ...

    @Override
    public void validate(final Object target, final Errors errors) {
        // custom validation
    }
}

最后是测试代码:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
    // tests
}

我遇到错误:

NoSuchBeanDefinitionException: No qualifying bean of type 'MyValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

我认为这个错误是合理的。我已将该测试注释为 WebMvcTest,我认为它已排除 @Component bean。这是有意的和需要的(从我只想测试“网络层”而不是整个上下文的角度来看 - 恰好我需要一个仅在 Controller 中相关/使用的组件)

因此,我的问题是:如何在 Web 测试的测试上下文中显式包含验证器等组件?

我的环境是 java version "10.0.2"2018-07-17,spring boot 1.5.16.RELEASE

最佳答案

web层有两种测试方式

首先。

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {
  @Autowired
  private MyController myController;
}

The @SpringBootTest annotation tells Spring Boot to go and look for a main configuration class (one with @SpringBootApplication for instance), and use that to start a Spring application context.

A nice feature of the Spring Test support is that the application context is cached in between tests, so if you have multiple methods in a test case, or multiple test cases with the same configuration, they only incur the cost of starting the application once. You can control the cache using the @DirtiesContext annotation.

其次,如果你想使用@WebMvcTest(MyController.class)

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

  @MockBean
  private MyValidator validator;

}

但是这个验证器是假的,所以你必须定制它来测试。

有关详细信息,请参阅此链接 https://spring.io/guides/gs/testing-web/

关于spring-boot - 有没有办法在 WebMvcTest 中包含一个 Spring 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52845174/

相关文章:

java - 无法将类型 "java.lang.Integer"编码(marshal)为元素,因为它缺少 @XmlRootElement 注释

spring-boot - 在 ServletContext 中找不到属性 ServerContainer

java - Spring 启动测试: run tasks before and after all tests

spring-boot - 如何使用Spring Boot从另一个文件夹加载静态资源

java - 使用 Resttemplate 的多个异步 HTTP 请求

java - 如何在 Spring 上传文件?

tomcat - 带有 Apache CXF 和 JNDI 查找 javax.naming.NameNotFoundException 的嵌入式 Tomcat 的 Spring Boot

java - Spring Boot 启用 http 请求日志记录(访问日志)

java - SpringBootTest 未在 Spring Boot 2 中回滚事务

java - 在使用 @SpringBootTest 运行的测试中定义 tomcat 属性