Skip to content

Support declarative PropertySource annotations in the TestContext framework [SPR-11377] #16004

Closed
@spring-projects-issues

Description

@spring-projects-issues

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:

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions