Defining an active spring profile in a test case

Using Spring 4, I have the following test setup:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JpaConfig.class)
@ActiveProfiles(resolver = TestResolver.class)
public class SimpleTest {

TestResolver is implemented as:

public class TestResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        String[] profiles = new String[1];
        profiles[0] = "test";
        return profiles;
    }
}

JpaConfig was annotated with PropertySource

@Configuration
@PropertySource("classpath:properties/application-${spring.profiles.active:dev}.properties")
@EnableJpaRepositories(basePackages={"com.my.namespace.repositories"})
public class JpaConfig {

Whenever I run SimpleTest, it tries to find: properties / application-dev.properties, while I expected that these are properties / application -test.properties.

What I'm trying to do here is based on the following post: Spring profile integration tests

+4
source share
2 answers

, , , , . . , ApplicationContextInitializer:

public class MyApplicationContextInitializer implements
    ApplicationContextInitializer<GenericApplicationContext> {

public void initialize(GenericApplicationContext context) {
    context.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "some_profile");
}

}

:

@ContextConfiguration(classes = JpaConfig.class, initializers = MyApplicationContextInitializer.class)

, ( .properties, ) SO- .

+10

, @PropertySource :

@PropertySource("classpath:properties/application-${spring.profiles.active}.properties")

( ) @ActiveProfile

@ActiveProfiles("test")
+1

Source: https://habr.com/ru/post/1537470/


All Articles