Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a spring active profile within a test use case

Using Spring 4, I've got the following test setup:

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

The TestResolver has been implemented as:

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

JpaConfig has been 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 the SimpleTest it tries to locate: properties/application-dev.properties while I expected it to be properties/application-test.properties.

What's I'm trying to accomplish here has been based on the following post: Spring integration tests with profile

like image 524
Jonas Geiregat Avatar asked Dec 15 '22 23:12

Jonas Geiregat


1 Answers

I believe this is, actually, the issue you are facing. And in that same post you have an explanation from Dave Syer and a possible solution from another user. To follow Dave's advice, this would be a possible implementation of an ApplicationContextInitializer:

public class MyApplicationContextInitializer implements
    ApplicationContextInitializer<GenericApplicationContext> {

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

}

and on your test class:

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

But I would say that the suggested approach (with different .properties files loaded for different profiles) in that SO post is a more elegant approach.

like image 87
Andrei Stefan Avatar answered Jan 27 '23 23:01

Andrei Stefan