You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support @TestPropertySource at method level [SPR-14378] #18951
@TestPropertySource allows you to set test-suite / class-level properties, but I want test-level properties so I can test drive classes with @ConditionalOnProperty and @Value(${var:default}) type annotations for correct behavior.
I have considered creating separate test suites for each test, but that seems unnatural. I currently manually manage the context within the test to validate the behavior.
Reacted by Mohammad Hewedy, Mike Meessen, OldIMP, Fırat Küçük, Julien Klaer, Simon Scholz, TG, Kevin Hooke, Adriano Scheffer, Hemani Katyal and 105 more
This would be really useful for me as well. I'm doing a lot of custom @AutoConfigure and managing different properties between tests is really tricky since @TestPropertySource only works on the class level.
Any plans on this? It would be very useful to not having to create a separate class each time an application.properties parameter should change for testing.
Reacted by Pablo Escobar, Elin Nilsson, buzzlighty, devarmy, Thomas Skjølberg, allainmagyar, Roman Haraiev, skydetulliov, Scott Feldstein, Cyrill Zadra and 37 more
Reacted by Artur Szkopek, srferron, Yousra S., Phat Nguyen, Daniel Eisenreich, James Murray, Raphael Amoedo, Gregory Povorozniuk, Sergiy Morenets and dng-dev
Reacted by Ronald Findling, Andrei Shchytliak, Phat Nguyen, Daniel Eisenreich, James Murray, srferron, Vladyslav Stusiak, Sergiy Morenets, Raphael Amoedo, Gregory Povorozniuk and 3 more
Reacted by Ronald Findling, CHOI,Leejun, Alex Kucksdorf, Artur Drummond, Oleg Iakovenko, Sergiy Morenets, Andrei Shchytliak, SteveWink, Phat Nguyen, Daniel Eisenreich and 15 more
Most developers resort to ReflectionTestUtils.setField(...) to work around this limitation, if the need happens to be to set just couple of properties.
importstaticcom.google.common.base.Preconditions.checkNotNull;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
importjava.lang.reflect.Method;
importjava.util.List;
importjava.util.Properties;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.cloud.context.config.annotation.RefreshScope;
importorg.springframework.cloud.context.refresh.ContextRefresher;
importorg.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
importorg.springframework.core.env.ConfigurableEnvironment;
importorg.springframework.core.env.PropertiesPropertySource;
importorg.springframework.test.annotation.DirtiesContext;
importorg.springframework.test.annotation.DirtiesContext.ClassMode;
importorg.springframework.test.annotation.DirtiesContext.MethodMode;
importorg.springframework.test.context.TestContext;
importorg.springframework.test.context.support.AbstractTestExecutionListener;
importcom.google.common.collect.ArrayListMultimap;
importcom.google.common.collect.Lists;
importcom.google.common.collect.Multimap;
/** * Note: the whole idea of test-method-specific properties is ONLY working if the consuming bean is initialized AFTER spring was able to add the property source to the context. Any other combination * of early initialized bean, constructor using properties etc. will not work. Even if you put a {@link RefreshScope} on such beans. The problem is how spring is calling this listener here. Its * sometimes simply too late. Maybe later if we really need/have refresh-able apps (consuming {@link RefreshScopeRefreshedEvent} etc.) then this can work. * * @author Andreas Höhmann */publicfinalclassTestPropertiesPerMethodHandlerextendsAbstractTestExecutionListener {
privatestaticfinalLoggerLOGGER = LoggerFactory.getLogger(TestPropertiesPerMethodHandler.class);
privatefinalMultimap<Method, PropertiesPropertySource> propertySources = ArrayListMultimap.create();
@Target({
ElementType.TYPE,
ElementType.METHOD
})
@Retention(RetentionPolicy.RUNTIME)
@DirtiesContext(methodMode = MethodMode.AFTER_METHOD, classMode = ClassMode.AFTER_CLASS)
public @interface TestProperties {
@Target({
ElementType.TYPE,
ElementType.METHOD
})
@Retention(RetentionPolicy.RUNTIME)
@DirtiesContext(methodMode = MethodMode.AFTER_METHOD, classMode = ClassMode.AFTER_CLASS)
public @interface TestProperty {
Stringname();
Stringvalue();
}
TestProperty[] value();
}
privatestaticList<PropertiesPropertySource> getTestProperties(finalMethodmethod) {
checkNotNull(method, "Method must not be null");
finalList<PropertiesPropertySource> result = Lists.newArrayList();
{
finalTestProperties[] allTestEnvironmentProperties = method.getAnnotationsByType(TestProperties.class);
if (allTestEnvironmentProperties != null) {
intc = 0;
for (finalTestPropertiestestEnvironmentProperties : allTestEnvironmentProperties) {
finalPropertiesproperties = newProperties();
for (finalTestPropertytestEnvironmentProperty : testEnvironmentProperties.value()) {
properties.put(testEnvironmentProperty.name(), testEnvironmentProperty.value());
}
if (!properties.isEmpty()) {
result.add(newPropertiesPropertySource(method.getName().toLowerCase() + "-" + c, properties));
c++;
}
}
}
}
{
finalTestProperty[] allTestEnvironmentProperties = method.getAnnotationsByType(TestProperty.class);
if (allTestEnvironmentProperties != null) {
finalPropertiesproperties = newProperties();
for (finalTestPropertytestEnvironmentProperty : allTestEnvironmentProperties) {
properties.put(testEnvironmentProperty.name(), testEnvironmentProperty.value());
}
if (!properties.isEmpty()) {
result.add(newPropertiesPropertySource(method.getName().toLowerCase(), properties));
}
}
}
returnresult;
}
@OverridepublicvoidbeforeTestMethod(finalTestContexttestContext) throwsException {
finalMethodtestMethod = testContext.getTestMethod();
booleanneedRefresh = false;
for (finalPropertiesPropertySourcepropertiesPropertySource : getTestProperties(testMethod)) {
LOGGER.info("Register additional property source '{}' with '{}' for method '{}'", propertiesPropertySource.getName(),
propertiesPropertySource.getSource(), testMethod);
((ConfigurableEnvironment) testContext.getApplicationContext().getEnvironment())
.getPropertySources()
.addFirst(propertiesPropertySource);
propertySources.put(testMethod, propertiesPropertySource);
needRefresh = true;
}
if (needRefresh) {
testContext.getApplicationContext().getBean(ContextRefresher.class).refresh();
}
}
@OverridepublicvoidafterTestMethod(finalTestContexttestContext) throwsException {
finalMethodtestMethod = testContext.getTestMethod();
booleanneedRefresh = false;
for (finalPropertiesPropertySourcepropertiesPropertySource : propertySources.removeAll(testMethod)) {
LOGGER.info("Unregister additional property source '{}' with '{}' for method '{}'", propertiesPropertySource.getName(),
propertiesPropertySource.getSource(), testMethod);
((ConfigurableEnvironment) testContext.getApplicationContext().getEnvironment())
.getPropertySources()
.remove(propertiesPropertySource.getName());
needRefresh = true;
if (needRefresh) {
testContext.getApplicationContext().getBean(ContextRefresher.class).refresh();
}
}
}
}
Activity
spring-projects-issues commentedon Feb 1, 2017
Seth Wingert commented
This would be really useful for me as well. I'm doing a lot of custom
@AutoConfigureand managing different properties between tests is really tricky since@TestPropertySourceonly works on the class level.spring-projects-issues commentedon Mar 22, 2017
vijay parashar commented
Any timeline for fixing this issue.
kodyrecords commentedon Aug 7, 2019
Any plans on this? It would be very useful to not having to create a separate class each time an application.properties parameter should change for testing.
RonaldFindling commentedon Mar 17, 2020
We would love to see this aswell
drodionov commentedon May 25, 2020
It would be great to have this feature!
srferron commentedon Jun 13, 2020
Yes, it´s needed
ben-pearson commentedon Jun 15, 2020
Yep, 4 years on, I want this too!
aarowman commentedon Oct 29, 2020
Any updates on this? Would really make testing simpler on conditional properties...
bruno-oliveira commentedon Dec 22, 2020
Bump
1 remaining item
blorp-goes-the-derp commentedon Jun 6, 2021
Also could use this feature!
ahoehma commentedon Jun 6, 2021
I have a working implementation for this.
vinay36999 commentedon Jun 11, 2021
Most developers resort to ReflectionTestUtils.setField(...) to work around this limitation, if the need happens to be to set just couple of properties.
pieterdb4477 commentedon Jul 20, 2021
This would be a great addition, indeed.
rahul-gupta-1525 commentedon Jul 27, 2021
good to have this in spring, looking forward to this
bbortt commentedon Sep 6, 2021
@ahoehma
would you mind sharing it? 😉
bfrggit commentedon Oct 27, 2021
Should be very helpful when testing some component with different configurations.
EarthCitizen commentedon Jan 19, 2022
This would be BEYOND incredible. No more nested static test classes just to have different properties for 1 or 2 tests!!!
EarthCitizen commentedon Jan 19, 2022
@sbrannen Any chance of getting this on the next minor version bump?
sbrannen commentedon Jan 19, 2022
The change would be too large for a point release. If we implement this, it would come in 6.x.
romerorsp commentedon Jun 10, 2022
It Will be great when you guys release that change in 6.x! I'd needed it now, but will figure another way of achieving the same goal.
sergey-morenets commentedon Jun 13, 2022
Hi @romerorsp
You can easily achieve this functionality if you use JUnit Jupiter. So you can just extract all the methods into inner class:
martinwunderlich-celonis commentedon Sep 9, 2024
any updates on this? would be a great feature to have.
ahoehma commentedon Sep 10, 2024
Let me share what I have here:
Example: