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 {
...
}
Unit test with Spring Boot 2
spring boot 2 support 'application.properties' by default, for 'application.yml' just add below:
e.g.
The trick to load any custom yml file in SpringBoot 2.0 w/o using
@SpringBootTest
ConfigFileApplicationContextInitializer
andspring.config.location
propertyExample Code:
For JUnit 5 use the
@ExtendWith(SpringExtension.class)
annotation instead of@RunWith(SpringRunner.class)
This works
Alternative in February 2017:
the lean variant (withouth
@SpringBootTest
):Here's another way: [Spring Boot v1.4.x]
This works ONLY if also 'application.properties' file exists.
e.g. maven project:
src/main/resources/application.properties [ The file can be empty but it's mandatory! ]
src/main/resources/application.yml [here's your real config file]
Try this:
EDIT:
For Spring Boot version 1.5+,
SpringApplicationConfiguration
was removed in favour ofSpringBootTest
or direct use ofSpringBootContextLoader
.You can still use
initializers
parameter withContextConfiguration
annotation.