Using Spring Boot 1.5.16 in WebMvcTest
I'm trying to load test.properties
applying @TestPropertySource
annotation in order to override some properties in test class. This works just fine if I put it on test class:
@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test.properties")
public class ControllerTest {
...
}
But properties not loaded if I move it to imported configuration:
@RunWith(SpringRunner.class)
@WebMvcTest
@Import(ControllersConfiguration.class)
public class ControllerTest {
...
}
and ControllersConfiguration
class is:
@TestConfiguration
@TestPropertySource("classpath:test.properties")
public class ControllersConfiguration {
...
}
Can you explain that behavior?
P.S. @PropertySource
annotation is working in imported configuration, but with lowest precedence than application.properties
UPD: To be clear - try to make all test pass here: https://github.com/Javasick/WeirdTestPropertySource
I investigated it yesterday and found that Spring is looking for this @TestPropertySource
annotation only on:
- Source test class
- Interfaces if test class implements them
- Superclases of this test class
- Inherited annotations
Here part of code from AbstractTestContextBootstrapper.class
that responsible for it:
MergedTestPropertySources mergedTestPropertySources =
TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
StringUtils.toStringArray(locations),
ClassUtils.toClassArray(classes),
ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
ActiveProfilesUtils.resolveActiveProfiles(testClass),
mergedTestPropertySources.getLocations(),
mergedTestPropertySources.getProperties(),
contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);
The method TestPropertySourceUtils.buildMergedTestPropertySources(testClass)
exactly responsible for finding and extracting location from this annotation. As you can see Spring invoke it only on test class.
So if you want to externalize this annotation you need to create super class and put this annotation and @Import
on it, or create interface with this annotation, or create your own annotation that will combine two annotation @Import
and @TestPropertySource
and put it on your test classes.