繁体   English   中英

Junit5 Spring Boot Autowire ComponentScan 不工作

[英]Junit5 Spring Boot Autowire ComponentScan Not Working

我的问题:如果我的测试是指@Bean在列出的类声明@SpringBootTest ,自动装配工作。 如果它自动引用@SpringBootTest列出的类的@ComponentScan类,则自动装配失败。 在测试之外,我的应用程序启动时没有自动装配或组件扫描问题,并且我可以确认我要在测试中加载的服务在非测试中运行良好。 我很沮丧。 我坏了,还是 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

尽管测试开始了,但我遇到了与自动装配不起作用的相同问题,问题是我仍在使用旧的 junit4 @Test 注释。 确保您的测试方法使用 juni5 包 org.junit.jupiter.api.Test 中的 @Test 进行注释。

我想是因为你已经这样注释了:

@SpringBootTest (classes=MyConfig.class)

Spring 只会在MyConfig.class查找适当的 beans,而无法为MyService找到一个,但是,我认为当应用程序正常运行时,Spring 将扫描所有包中的 bean。 这就是它在非测试中工作正常的原因。

就像@Tudro说, org.junit.jupiter.api.Test是Junit的5 org.junit.Test是JUnit 4中。

在下面使用这个:

@ExtendedWith(SpringExtension.class)
@SpringBootTest

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM