Spring Testing - @ActiveProfiles Example

[Updated: Jul 1, 2017, Created: Jul 1, 2017]

This example demonstrates how to use @ActiveProfiles.

@ActiveProfiles is a class-level annotation that is used to specify which profile should be selected when loading an ApplicationContext for test classes.

Example

Creating a Spring Profile based application

@Configuration
public class AppConfig {

  @Bean
  @Profile(PROFILE_LOCAL)
  public DataService dataServiceLocal() {
      return DataServiceLocal.Instance;
  }

  @Bean
  @Profile(PROFILE_REMOTE)
  public DataService dataServiceRemote() {
      return DataServiceRemote.Instance;
  }

  public static final String PROFILE_LOCAL = "local";
  public static final String PROFILE_REMOTE = "remote";
}
@Service
public interface DataService {
  List<Customer> getCustomersByAge(int minAge, int maxAge);
}
public class Customer {
  private long customerId;
  private String name;
  private int age;
    .............
}
@Configuration
@ComponentScan("com.logicbig.example")
public class AppConfig {
}

The JUnit test

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@ActiveProfiles(AppConfig.PROFILE_LOCAL)
public class DataServiceTests {

  @Autowired
  private DataService dataService;

  @Test
  public void testCustomerAges() {
      List<Customer> customers = dataService.getCustomersByAge(25, 40);
      for (Customer customer : customers) {
          int age = customer.getAge();
          Assert.assertTrue("Age range is not 25 to 40: " + customer,
                  age >= 25 && age < 40);
      }
  }
}
mvn  -q test -Dtest=DataServiceTests

Output

D:\example-projects\spring-core-testing\spring-test-active-profile>mvn  -q test -Dtest=DataServiceTests

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.DataServiceTests
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.408 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 Example Select All Download
  • spring-test-active-profile
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example

See Also