difference in setProperty and ActiveProfiles annotation for junit testing

305 views Asked by At

I have config files for my different environmnets: prod.properties, dev.propertites, and test.properties.

Properties file is loaded via application-context.xml file using

${spring.profiles.active}.properties

and passing in -Dspring.profiles.active flag. This works file for my 3 environments.

For Junit testing I'm trying to use

@ActiveProfiles("test")

in my test class but $(spring.profiles.active) is not resolving. But when I use

System.getProperties().setProperty("spring.profiles.active", "test");

it resolved fine.

I know @ActiveProfiles is only for test classes but why doesn't it set the spring.profiles.active property? Does it only affect which beans to use?

This also doesn't clarify who best to handle profiles and property files. Spring profiles and Testing

Update: I have so far resorted to using the following in my application context file:

<beans profile="dev,prod">
<context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/${spring.profiles.active}/${spring.profiles.active}.properties"/>
        <context:component-scan base-package="com.my.package.to.scan"/>
 </beans>       

<beans profile="test">
    <context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/test/test.properties"/>
<context:component-scan base-package="com.my.package.to.scan"/>
</beans>
1

There are 1 answers

4
Rohit On

As the name suggest @ActiveProfiles, this is array of profiles.

/**
 * The bean definition profiles to activate.
 * <p>This attribute may <strong>not</strong> be used in conjunction with
 * {@link #value}, but it may be used <em>instead</em> of {@link #value}.
 */
@AliasFor("value")
String[] profiles() default {};

Try with @ActiveProfiles({"test"}).