Search code examples
javaspringjunit5spring-boot-test

Junit5 Spring Boot Autowire ComponentScan Not Working


My problem: if my test refers to an @Bean declaration in the class listed in @SpringBootTest, autowire works. If it refers to a class automatically @ComponentScanned by the class listed in @SpringBootTest, autowire fails. Outside of testing, my app starts without autowire or componentscan issues, and I can confirm that the service I want to load in my test runs fine from non-test. I'm frustrated as hell. Am I broken, or is Junit5 functionality on Spring Boot 2?

My Test:

@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

Solution

  • I had the same issue with autowiring not working although the test was starting and the problem was that I was still using the old junit4 @Test annotation. Make sure your test method is annotated with @Test from juni5 package org.junit.jupiter.api.Test.