Spring Boot properties in 'application.yml' not loading from JUnit Test

aliopi picture aliopi · Oct 19, 2015 · Viewed 82.9k times · Source

What am I doing wrong? I'm using this little standalone App which runs and finds my src/main/resources/config/application.yml. The same configuration doesn't work from JUnit, see below:

@Configuration
@ComponentScan
@EnableConfigurationProperties

public class TestApplication {

    public static void main(String[] args) {

        SpringApplication.run(TestApplication.class);
    }
}


@Component
@ConfigurationProperties

public class Bean{
    ...
}

The following doesn't work, the same properties in application.yml are not loaded and Bean has only null values:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)

public class SomeTestClass {
    ...
}

Answer

luboskrnac picture luboskrnac · Oct 19, 2015

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestApplication.class, 
    initializers = ConfigFileApplicationContextInitializer.class)
public class SomeTestClass {
    ...
}

EDIT:

For Spring Boot version 1.5+, SpringApplicationConfiguration was removed in favour of SpringBootTest or direct use of SpringBootContextLoader.

You can still use initializers parameter with ContextConfiguration annotation.