Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

I think you should change @PropertySource to:

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

Also for simplicity (shouldn't have any effect on how the code runs) your @ActiveProfile could be

@ActiveProfiles("test")
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top