我的问题:如果我的测试引用了@Bean
中列出的类中的@SpringBootTest
声明,则自动装配有效。如果它引用由@ComponentScan
中列出的类自动@SpringBootTest
定义的类,则自动装配失败。在测试之外,我的应用程序启动时不会出现自动装配或组件扫描问题,并且我可以确认要在测试中加载的服务在非测试中运行良好。我为地狱感到沮丧。我是否坏了,还是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 ;
MyConfig:
@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
最佳答案
尽管测试正在启动,但我仍然遇到自动装配无法正常工作的问题,问题是我仍在使用旧的junit4 @Test批注。
确保您的测试方法使用来自juni5包org.junit.jupiter.api.Test的@Test注释。