Close

Spring Testing - Resolving active profiles programmatically by using ActiveProfilesResolver

[Last Updated: Jul 17, 2017]

ActiveProfilesResolver interface can be implemented to programmatically select profiles for Spring Tests. We can register our ActiveProfilesResolver implementation with the 'resolver' attribute of @ActiveProfiles annotation. Let's see an example how to do that.

Example

Creating a simple Spring application

@Configuration
public class AppConfig {
  @Bean
  @Profile("windows")
  public MyService myServiceA() {
      return new MyServiceA();
  }

  @Bean
  @Profile("other")
  public MyService myServiceB() {
      return new MyServiceB();
  }
}
public interface MyService {
  public String doSomething();
}
public class MyServiceA implements MyService {
  @Override
  public String doSomething() {
      return "in " + this.getClass().getSimpleName();
  }
}
public class MyServiceB implements MyService {
  @Override
  public String doSomething() {
      return "in " + this.getClass().getSimpleName();
  }
}

Implementing MyActiveProfilesResolver

public class MyActiveProfilesResolver  implements ActiveProfilesResolver{
  @Override
  public String[] resolve(Class<?> testClass) {
      String os = System.getProperty("os.name");
      String profile = (os.toLowerCase().startsWith("windows")) ? "windows" : "other";
      return new String[]{profile};
  }
}

The JUnit test

Following test will fail if run other than Windows O.S.

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@ActiveProfiles(resolver = MyActiveProfilesResolver.class)
public class MyServiceTests {

  @Autowired
  private MyService dataService;

  @Test
  public void testDoSomething() {
      String s = dataService.doSomething();
      System.out.println(s);
      Assert.assertEquals("in MyServiceA", s);
  }
}
mvn  -q test -Dtest=MyServiceTests

Output

d:\example-projects\spring-core-testing\active-profile-resolver-example>mvn  -q test -Dtest=MyServiceTests

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.MyServiceTests
in MyServiceA
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.371 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.9.RELEASE: Spring Context.
  • spring-test 4.3.9.RELEASE: Spring TestContext Framework.
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Spring Test Active Profiles Resolver Example Select All Download
  • active-profile-resolver-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example
                • MyActiveProfilesResolver.java

    See Also