1. Overview

It’s common to create different configurations for different stages of the development and deployment process. In fact, when we are deploying a Spring application, we can assign a Spring Profile to each stage and create dedicated tests.

In this tutorial, we’ll focus on executing tests based on active Spring Profile using JUnit 5.

2. Project Setup

First of all, let’s add to our project the spring-boot-starter-web dependency:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Now let’s create a simple Spring Boot application:

@SpringBootApplication
public class ActiveProfileApplication {

    public static void main (String [] args){
        SpringApplication.run(Application.class);
    }
}

Finally, let’s create an application.yaml file to serve as our default properties source file.

3. Spring Profile

Spring Profile provides a way to define and manage different environments by grouping configuration settings specific to each environment.

In fact, by activating a specific profile, we can easily switch between different configurations and settings.

3.1. Active Profile on Properties File

We can specify the active profile in the application.yaml file:

spring:
  profiles:
    active: dev

So now Spring will retrieve all the properties for the active profile and load all the dedicated beans into the application context.

In this tutorial, we’ll create a dedicated properties file for each profile. That’s because having dedicated files for each profile simplifies the process of managing and updating the configuration for each specific environment.

So let’s create two profiles for the test and prod environments, each with the profile.property.value property, but with a different value that corresponds to the name of the file.

So let’s create an application-prod.yaml file and add the profile.property.value property:

profile:
  property:
    value: This the the application-prod.yaml file

Similarly, we do the same for application-test.yaml:

profile:
  property:
    value: This the the application-test.yaml file

Finally, let’s add the same property to the application.yaml:

profile:
  property:
    value: This the the application.yaml file

Now let’s write a simple test to verify that the application behaves as expected in this environment:

@SpringBootTest(classes = ActiveProfileApplication.class)
public class DevActiveProfileUnitTest {

    @Value("${profile.property.value}")
    private String propertyString;

    @Test
    void whenDevIsActive_thenValueShouldBeKeptFromApplicationYaml() {
        Assertions.assertEquals("This the the application.yaml file", propertyString);
    }
}

The value injected into the variable propertyString is sourced from the property value defined in application.yaml. That’s because dev is the profile activated during the test execution and no properties file was defined for this profile.

3.2. Set an Active Profile on A Test Class

By setting the spring.profiles.active property, we can activate the corresponding profile and load the configuration files associated with it.

But, in certain instances, we may want to execute test classes with a specific profile, overriding the active profile defined in the properties file.

So we can use @ActiveProfiles, an annotation compatible with JUnit 5, that declares the active profiles to use when loading an application context for test classes.

So if we annotate a test class with the @ActiveProfiles annotation and set the value attribute to test, all tests in the class will use the test profile:

@SpringBootTest(classes = ActiveProfileApplication.class)
@ActiveProfiles(value = "test")
public class TestActiveProfileUnitTest {

    @Value("${profile.property.value}")
    private String propertyString;

    @Test
    void whenTestIsActive_thenValueShouldBeKeptFromApplicationTestYaml() {
        Assertions.assertEquals("This the the application-test.yaml file", propertyString);
    }
}

The value attribute, which is an alias of the profiles attribute, is an array of strings. That’s because it’s possible to specify more than one active profile by using a comma-separated list.

For example, if we want to specify the active profiles as test and prod, we can use:

@ActiveProfiles({"prod", "test"})

In this way, the application context is configured using the properties and configurations specific to the test and prod profiles.

The configurations will be applied in the order they are listed. In case of conflict between the configurations of different profiles, the one defined for the last listed profile will take precedence.

So running tests based on the active profile is essential to ensure that the application behaves correctly in different environments. However, executing tests designed for specific profiles in other environments can pose a significant risk. For example, when running tests on a local machine, we may unintentionally run tests designed for the production environment.

To avoid this scenario, we need to find a way to filter test execution based on the active profile.

4. @EnabledIf Annotation

In JUnit 4, it’s possible to execute tests conditionally using the @IfProfileValue annotation. In fact, it specifies a condition that must be met in order for the test to be executed.

But when our unit-test framework is JUnit 5, we should avoid using @IfProfileValue, because it’s no longer supported on the current version.

So we can instead use @EnabledIf, **an annotation that enables or disables a method or class based on a condition.
**

Junit 5 also offers the @EnabledIf annotation. Therefore, we should ensure that we’re importing the one provided by Spring to avoid any confusion.

This annotation has the following attributes:

  • value: the condition expression that should be true in order to enable the test class or single test
  • expression: it also specifies the condition expression. In fact, it’s marked as @AliasFor
  • loadContext: specify whether or not the context needs to be loaded in order to evaluate the condition. The default value is false
  • reason: the explanation for why the condition is required

In order to evaluate conditions that use values defined in the Spring application context, like the active profiles, we should set to true the boolean attribute loadContext.

4.1. Run Tests for A Single Profile

If we want to run our test class only when a single profile is active, we can evaluate the attribute value with the SPEL function:

#{environment.getActiveProfiles()[0] == 'prod'}

In this function, the environment variable is an object that implements Enviroment. So environment.getActiveProfiles() returns an array of active profiles in the current environment, and [0] accesses the first element of that array.

So let’s add the annotation to our test:

@SpringBootTest(classes = ActiveProfileApplication.class)
@EnabledIf(value = "#{environment.getActiveProfiles()[0] == 'prod'}", loadContext = true)
public class ProdActiveProfileUnitTest {

    @Value("${profile.property.value}")
    private String propertyString;

    @Test
    void whenProdIsActive_thenValueShouldBeKeptFromApplicationProdYaml() {
        Assertions.assertEquals("This the the application-prod.yaml file", propertyString);
    }

}

Then, let’s activate the prod profile via @ActiveProfiles:

@SpringBootTest(classes = ActiveProfileApplication.class)
@EnabledIf(value = "#{environment.getActiveProfiles()[0] == 'prod'}", loadContext = true)
@ActiveProfiles(value = "prod")
public class ProdActiveProfileUnitTest {

    @Value("${profile.property.value}")
    private String propertyString;

    @Test
    void whenProdIsActive_thenValueShouldBeKeptFromApplicationProdYaml() {
        Assertions.assertEquals("This the the application-prod.yaml file", propertyString);
    }

}

So, the tests in our class will always run with the configurations specified for the prod profile and when the current profile is actually prod.

4.2. Run Tests for Multiple Profiles

If we want to execute our tests under different active profiles, we can evaluate the value or expression attributes with the SPEL function:

#{{'test', 'prod'}.contains(environment.getActiveProfiles()[0])}

Let’s break down the function:

  • {‘test’,’prod’} defines a set of two profile names defined in our Spring application
  • .contains{environment-getActiveProfiles()[0]} checks whether the first element of the array is contained within the set defined earlier

So let’s add to our test class the @EnableIf annotation:

@SpringBootTest(classes = ActiveProfileApplication.class)
@EnabledIf(value = "#{{'test', 'prod'}.contains(environment.getActiveProfiles()[0])}", loadContext = true)
@ActiveProfiles(value = "test")
public class MultipleActiveProfileUnitTest {
    @Value("${profile.property.value}")
    private String propertyString;

    @Autowired
    private Environment env;

    @Test
    void whenDevIsActive_thenValueShouldBeKeptFromDedicatedApplicationYaml() {
        String currentProfile = env.getActiveProfiles()[0];
        Assertions.assertEquals(String.format("This the the application-%s.yaml file", currentProfile), propertyString);
    }
}

So, the tests in our class will always run when the active profile is test or prod.

5. Conclusion

In this article, we saw how to execute tests based on the active Spring profile using JUnit 5 annotation. We learned how to enable profiles on test classes and how we can execute them if one or more specific profiles are active.

As always, the complete source code of the examples can be found over on GitHub.