This is a similar but further question with how to run/turn off selective tests based on profiles in spring boot.
I know the @IfProfileValue
annotation provides the ability to enable test based on some conditions, but the properties it get are from System.properties
and the spring.profiles.active
is not in it.
I also know we can use @ProfileValueSourceConfiguration
to customise the ProfileValueSource
like below:
Test
@RunWith(SpringRunner.class)
@SpringBootTest
@ProfileValueSourceConfiguration(value = SpringProfileValueSource.class)
@IfProfileValue(name = "spring.profiles.active", value = "test")
public class MyTest {
// some tests
}
Custom ProfileValueSource
public class SpringProfileValueSource implements ProfileValueSource {
@Override
public String get(String key) {
Environment environment = StaticSpringContext.applicationContext.getEnvironment();
return environment.getProperty(key);
}
}
Since the SpringProfileValueSource
will be created outside of Spring, so I created the following class to get Spring context:
StaticSpringContext
@Configuration
public class StaticSpringContext implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
StaticSpringContext.applicationContext = applicationContext;
}
}
However, seems all the properties check happens before Spring get started, so the applicationContext
in StaticSpringContext
is actually null when I use it in SpringProfileValueSource
.
I thought it was a common situation to enable tests based on spring profiles, but I did many search and still don't know how to do it. Any ideas? With many thanks.