【发布时间】:2018-09-19 12:45:36
【问题描述】:
我的问题:如果我的测试引用了@SpringBootTest 中列出的类中的@Bean 声明,则自动装配可以工作。如果它通过@SpringBootTest 中列出的类自动引用一个类@ComponentScanned,则自动装配失败。在测试之外,我的应用程序在没有自动装配或组件扫描问题的情况下启动,并且我可以确认我想要在我的测试中加载的服务在非测试中运行良好。我很沮丧。我是坏了,还是 Spring Boot 2 上的 Junit5 功能?
我的测试:
@ExtendWith(SpringExtension.class)
@SpringBootTest (classes=MyConfig.class)
public class MyTest {
// fails to autowire
@Autowired
private MyService _mySvc ;
// succeeds!
@Autowired @Qualifier ( "wtf" )
private String _wtf ;
我的配置:
@EnableWebMvc
@SpringBootApplication ( scanBasePackages = "my.packaging" )
@Configuration
public class MyConfig {
@Bean
public String wtf ( ) { return "W T F???" ; }
// No @Bean for MyService because component scan is nicer in the non-test world
【问题讨论】:
-
@RunWith(SpringRunner.class) @SpringBootTest(classes = MyConfig .class) 试试这个
-
SpringRunner 是 Junit4。
-
就此而言,@RunWith 也是如此。删除它不会改变任何东西,所以我把它从我的样本中取出。
标签: java spring junit5 spring-boot-test