eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)