Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Set an Environment Variable at Runtime in Java

$
0
0

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.

As usual, all the code from this tutorial is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles