Closed
Description
Shevek opened SPR-11377 and commented
I wrote this ages ago, but:
There should be an equivalent of @ActiveProfiles
for PropertySources
. I wrote this code, and hope it helps.
public class CustomTestContextLoader extends DelegatingSmartContextLoader {
private final SmartContextLoader annotationConfigLoader = new AnnotationConfigContextLoader() {
@Override
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
super.prepareContext(context, mergedConfig);
Class<?> testClass = mergedConfig.getTestClass();
Map<String, Object> properties = new HashMap<String, Object>();
TestPropertyValues values = AnnotationUtils.getAnnotation(testClass, TestPropertyValues.class);
if (values != null)
for (TestPropertyValue value : values.value())
properties.put(value.name(), value.value());
TestPropertyValue value = AnnotationUtils.getAnnotation(testClass, TestPropertyValue.class);
if (value != null)
properties.put(value.name(), value.value());
if (!properties.isEmpty()) {
MapPropertySource source = new MapPropertySource(TestPropertyValues.class.getSimpleName(), properties);
context.getEnvironment().getPropertySources().addFirst(source);
}
}
};
@Override
protected SmartContextLoader getAnnotationConfigLoader() {
return annotationConfigLoader;
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TestPropertyValues {
TestPropertyValue[] value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface TestPropertyValue {
String name();
String value();
}
Then it's used like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = CustomTestContextLoader.class,
classes = {...})
@TestPropertyValues({
@TestPropertyValue(name = "key", value = "value"),
@TestPropertyValue(name = "foo", value = "bar")
})
public class MyTest { ... }
Can we have a better integrated equivalent of this in the default DelegatingSmartContextLoader
, or wherever you feel appropriate, please? It would help us IMMENSELY.
Thank you.
Affects: 3.2.7
Issue Links:
- Allow @PropertySource to be specified on a test class [SPR-10232] #14865 Allow
@PropertySource
to be specified on a test class - Allow the use of custom PropertySource annotations in @Configuration classes [SPR-8963] #13603 Allow the use of custom PropertySource annotations in
@Configuration
classes - Introduce @TestPropertySource support in the TestContext framework [SPR-12051] #16667 Introduce
@TestPropertySource
support in the TestContext framework ("is superseded by")