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 {
...
}
Spring boot 2 example:
adding to Liam's answer, an alternative will be:
the key difference here is that the test will fail with a file not found exception if
application.yaml
is not in your/test/resources
directoryIn my case I was trying to test a library without a
@SpringBootApp
declared in the regular app classpath, but I do have one in my test context. After debugging my way through the Spring Boot initialization process, I discovered that Spring Boot's YamlPropertySourceLoader (as of 1.5.2.RELEASE) will not load YAML properties unlessorg.yaml.snakeyaml.Yaml
is on the classpath. The solution for me was to add snakeyaml as a test dependency in my POM: