There are several solutions. The easiest and self-describing is based on spring.config.location
property. @TestPropertySource
has highest precedence, so the property goes there.
Following example demonstrates minimal Spring Boot test:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(initializers = {ConfigDataApplicationContextInitializer.class})
@TestPropertySource(properties = {"spring.config.location=classpath:debug.yml"})
@EnableConfigurationProperties({DataSourceProperties.class})
public class MyTest {
@Autowired DataSourceProperties dbProps;
@Test
public void test() {
System.out.println(dbProps.getUrl());
}
}
ConfigDataApplicationContextInitializer
is hidden when you use @SpringBootTest
. @EnableConfigurationProperties
is here because we slicing execution environment to minimum (no auto-scanning!).
spring.config.location
property overrides default search strategy, like classpath:application.yml
- nice if you want a completely separated config!
spring.config.location
allows to specify a list of locations with comma:
classpath:common.yml,file:./config/local.yml
Some control is possible with spring.config.name
.
Another way is to use @PropertySource(factory = ...)
for YAML files (because Spring Framework only supports XML & .properties
config files):
@PropertySource(value = {"file:./local.yml"}, factory = MyTest.YamlPropertySourceFactory.class)
public class MyTest {
public static class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
return new PropertiesPropertySource(resource.getResource().getFilename(), factory.getObject());
}
}
...
}