Having trouble mocking System.getenv calls in junit

Viewed 22729

I'm trying to write a unit test with junit and mockito (very new to this) for a Spring Boot application. Basically in my code, I have specified an environment variable for a specific URL in a manifest.yml file (for deployment) that I can access through String URL = System.getenv("VARIABLE") in my code. I'm having a lot of trouble with my unit testing however, since the URL variable is obviously undefined. I tried the solution here, but realized this is only for mocking an environment variable if you're calling it from the actual test itself, not if you're relying on the environment variable being accessible from the code.

Is there any way to set it up so that when the test is run, I can set environment variables that can be accessed within the code?

2 Answers

This can be achieved with https://github.com/webcompere/system-stubs

You have a couple of options:

EnvironmentVariables environmentVariables = new EnvironmentVariables("VARIABLE", "http://testurl");

// then put the test code inside an execute method
environmentVariables.execute(() -> {
   // inside here, the VARIABLE will contain the test value
});

// out here, the system variables are back to normal

Or it can be done with a JUnit4 or 5 plugin:

@ExtendWith(SystemStubsExtension.class)
class SomeTest {

    @SystemStub
    private EnvironmentVariables environment = new EnvironmentVariables("VARIABLE", "http://testurl");

    @Test
    void someTest() {
        // inside the test the variable is set
        // we can also change environment variables:

        environment.set("OTHER", "value");
    }

}
Related