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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Java provides a simple way of interacting with environment variables. We can access them but cannot change them easily. However, in some cases, we need more control over the environment variables, especially for test scenarios.

In this tutorial, we’ll learn how to address this problem and programmatically set or change environment variables. We’ll be talking only about using it in a testing context. Using dynamic environment variables for domain logic should be discouraged, as it is prone to problems.

2. Accessing Environment Variables

The process of accessing the environment variables is pretty straightforward. The System class provides us with such functionality:

@Test
void givenOS_whenGetPath_thenVariableIsPresent() {
    String classPath = System.getenv("PATH");
    assertThat(classPath).isNotNull();
}

Also, if we need to access all variables, we can do this:

@Test
void givenOS_whenGetEnv_thenVariablesArePresent() {
    Map<String, String> environment = System.getenv();
    assertThat(environment).isNotNull();
}

However, the System doesn’t expose any setters, and the Map we receive is unmodifiable.

3. Changing Environment Variables

We can have different cases where we want to change or set an environment variable. As our processes are involved in a hierarchy, thus we have three options:

  • a child process changes/sets the environment variable of a parent
  • a process changes/sets its environment variables
  • a parent process changes/sets the environment variables of a child

We’ll talk only about the last two cases. The first one is more complex and cannot be easily rationalized for test purposes. Also, it generally cannot be achieved in pure Java and often involves some advanced coding in C/C++.

We’ll concentrate only on Java solutions to this problem. Although JNI is part of Java, it’s more involved, and the solution should be implemented in C/C++. Also, the solution might have issues with portability. That’s why we won’t investigate these approaches in detail.

4. Current Process

Here, we have several options. Some of them might be viewed as hacks, as it’s not guaranteed that they will work on all the platforms.

4.1. Using Reflection API

Technically, we can change the System class to ensure that it will provide us with the values we need using Reflection API:

@SuppressWarnings("unchecked")
private static Map<String, String> getModifiableEnvironment()
  throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    Class<?> environmentClass = Class.forName(PROCESS_ENVIRONMENT);
    Field environmentField = environmentClass.getDeclaredField(ENVIRONMENT);
    assertThat(environmentField).isNotNull();
    environmentField.setAccessible(true);

    Object unmodifiableEnvironmentMap = environmentField.get(STATIC_METHOD);
    assertThat(unmodifiableEnvironmentMap).isNotNull();
    assertThat(unmodifiableEnvironmentMap).isInstanceOf(UMODIFIABLE_MAP_CLASS);

    Field underlyingMapField = unmodifiableEnvironmentMap.getClass().getDeclaredField(SOURCE_MAP);
    underlyingMapField.setAccessible(true);
    Object underlyingMap = underlyingMapField.get(unmodifiableEnvironmentMap);
    assertThat(underlyingMap).isNotNull();
    assertThat(underlyingMap).isInstanceOf(MAP_CLASS);

    return (Map<String, String>) underlyingMap;
}

However, this approach would break the boundaries of modules. Thus, on Java 9 and above, it might result in a warning, but the code will compile. While in Java 16 and above, it throws an error:

java.lang.reflect.InaccessibleObjectException: 
Unable to make field private static final java.util.Map java.lang.ProcessEnvironment.theUnmodifiableEnvironment accessible: 
module java.base does not "opens java.lang" to unnamed module @2c9f9fb0

To overcome the latter problem, we need to open the system modules for reflective access. We can use the following VM options:

--add-opens java.base/java.util=ALL-UNNAMED 
--add-opens java.base/java.lang=ALL-UNNAMED

While running this code from a module, we can use its name instead of ALL-UNNAMED.

However, the getenv(String) implementation might differ from platform to platform. Also, we don’t have any guarantees about the API of internal classes, so the solution might not work in all setups.

To save some typing, we can use an already implemented solution from the JUnit Pioneer library:

<dependency>
    <groupId>org.junit-pioneer</groupId>
    <artifactId>junit-pioneer</artifactId>
    <version>2.2.0</version>
    <scope>test</scope>
</dependency>

It uses a similar idea but offers a more declarative approach:

@Test
@SetEnvironmentVariable(key = ENV_VARIABLE_NAME, value = ENV_VARIABLE_VALUE)
void givenVariableSet_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
    String actual = System.getenv(ENV_VARIABLE_NAME);
    assertThat(actual).isEqualTo(ENB_VARIABLE_VALUE);
}

@SetEnvironmentVariable helps us to define the environment variables. However, because it uses reflection, we have to provide access to the closed modules as we did previously.

4.2. JNI

Another approach is to use JNI and implement the code that would set the environment variables using C/C++. It’s a more invasive approach and requires minimal C/C++ skills. At the same time, it doesn’t have a problem with reflexive access.

However, we cannot guarantee that it will update the variables in Java runtime. Our application can cache the variables on startup, and any further changes won’t have any effect. We don’t have this problem while changing the underlying Map using reflection, as it changes the value only on the Java side.

Also, this approach would require a custom solution for different platforms. Because all OSs handle environment variables differently, the solution won’t be as cross-platform as the pure Java implementation.

5. Child Process

ProcessBuilder can help us to create a child process directly from Java. It’s possible to run any process with it. However, we’ll use it to run our JUnit tests:

@Test
void givenChildProcessTestRunner_whenRunTheTest_thenAllSucceed()
  throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.inheritIO();

    Map<String, String> environment = processBuilder.environment();
    environment.put(CHILD_PROCESS_CONDITION, CHILD_PROCESS_VALUE);
    environment.put(ENVIRONMENT_VARIABLE_NAME, ENVIRONMENT_VARIABLE_VALUE);
    Process process = processBuilder.command(arguments).start();

    int errorCode = process.waitFor();
    assertThat(errorCode).isZero();
}

ProcessBuilder provides API to access environment variables and start a separate process. We can even run a Maven test goal and identify which tests we want to execute:

public static final String CHILD_PROCESS_TAG = "child_process";
public static final String TAG = String.format("-Dgroups=%s", CHILD_PROCESS_TAG);
private final String testClass = String.format("-Dtest=%s", getClass().getName());
private final String[] arguments = {"mvn", "test", TAG, testClass};

This process picks up the tests in the same class with a specific tag:

@Test
@EnabledIfEnvironmentVariable(named = CHILD_PROCESS_CONDITION, matches = CHILD_PROCESS_VALUE)
@Tag(CHILD_PROCESS_TAG)
void givenChildProcess_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
    String actual = System.getenv(ENVIRONMENT_VARIABLE_NAME);
    assertThat(actual).isEqualTo(ENVIRONMENT_VARIABLE_VALUE);
}

It’s possible to customize this solution and tailor it to specific requirements.

6. Docker Environment

However, if we need more configuration or a more specific environment, it’s better to use Docker and Testcontainers. It would provide us with more control, especially with integration tests. Let’s outline the Dockerfile first:

FROM maven:3.9-amazoncorretto-17
WORKDIR /app
COPY /src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java \
 ./src/test/java/com/baeldung/setenvironment/
COPY /docker-pom.xml ./
ENV CUSTOM_DOCKER_ENV_VARIABLE=TRUE
ENTRYPOINT mvn -f docker-pom.xml test

We’ll copy the required test and run it inside a container. Also, we provide environment variables in the same file.

We can use a CI/CD setup to pick up the container or Testcontainers inside our tests to run the test. While it’s not the most elegant solution, it might help us run all the tests in a single click. Let’s consider a simplistic example:

class SettingTestcontainerVariableUnitTest {
    public static final String CONTAINER_REPORT_FILE = "/app/target/surefire-reports/TEST-com.baeldung.setenvironment.SettingDockerEnvironmentVariableUnitTest.xml";
    public static final String HOST_REPORT_FILE = "./container-test-report.xml";
    public static final String DOCKERFILE = "./Dockerfile";

    @Test
    void givenTestcontainerEnvironment_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
        Path dockerfilePath = Paths.get(DOCKERFILE);
        GenericContainer container = new GenericContainer(
          new ImageFromDockerfile().withDockerfile(dockerfilePath));
        assertThat(container).isNotNull();
        container.start();
        while (container.isRunning()) {
            // Busy spin
        }
        container.copyFileFromContainer(CONTAINER_REPORT_FILE, HOST_REPORT_FILE);
    }
}

However, containers don’t provide a convenient API to copy a folder to get all reports. The simplest way to do this is the withFileSystemBind() method, but it’s deprecated. Another approach is to create a bind in the Dockerfile directly.

We can rewrite the example using ProcessBuillder. The main idea is to tie the Docker and usual tests into the same suite. 

7. Conclusion

Java allows us to work with the environment variables directly. However, changing their values or setting new ones isn’t easy.

If we need this in our domain logic, it signals that we’ve violated several SOLID principles in most cases. However, during testing, more control over environment variables might simplify the process and allow us to check more specific cases.

Although we can use reflection, spinning a new process or building an entirely new environment using Docker is a more appropriate solution.

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.

Course – LS – NPI (cat=Java)
announcement - icon

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

>> CHECK OUT THE COURSE

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