给定生产代码类:
@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/