The @ClearEnvironmentVariable and @SetEnvironmentVariable annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn’t have one before. Other environment variables that are changed during the test, are not restored.

Warning
Java considers environment variables to be immutable, so this extension uses reflection to change them. This requires that the SecurityManager allows modifications and can potentially break on different operating systems and Java versions. Be aware that this is a fragile solution and consider finding a better one for your specific situation. If you’re running on Java 9 or later, you may have to add --add-opens=java.base/java.util=ALL-UNNAMED to your test execution to prevent warnings or even errors.

For example, clearing a environment variable for a test execution can be done as follows:

@Test
@ClearEnvironmentVariable(key = "some variable")
void test() {
	assertThat(System.getenv("some variable")).isNull();
}

And setting a environment variable for a test execution:

@Test
@SetEnvironmentVariable(key = "some variable", value = "new value")
void test() {
	assertThat(System.getenv("some variable")).isEqualsTo("new value");
}

As mentioned before, both annotations are repeatable and they can also be combined:

@Test
@ClearEnvironmentVariable(key = "1st variable")
@ClearEnvironmentVariable(key = "2nd variable")
@SetEnvironmentVariable(key = "3rd variable", value = "new value")
void test() {
	assertThat(System.getenv("1st variable")).isNull();
	assertThat(System.getenv("2nd variable")).isNull();
	assertThat(System.getenv("3rd variable")).isEqualsTo("new value");
}

Note that class level configurations are overwritten by method level configurations:

@ClearEnvironmentVariable(key = "some variable")
class MyEnvironmentVariableTest {
	@Test
	@SetEnvironmentVariable(key = "some variable", value = "new value")
	void test() {
		assertThat(System.getenv("some variable")).isEqualsTo("new value");
	}
}