Having trouble mocking System.getenv calls in juni

2019-05-06 21:26发布

问题:

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?

回答1:

You can use PowerMockito to mock static methods. This code demonstrates mocking the System class and stubbing getenv()

@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class})
public class Xxx {

    @Test
    public void testThis() throws Exception {
        System.setProperty("test-prop", "test-value");
        PowerMockito.mockStatic(System.class);

        PowerMockito.when(System.getenv(Mockito.eq("name"))).thenReturn("bart");
        // you will need to do this (thenCallRealMethod()) for all the other methods
        PowerMockito.when(System.getProperty(Mockito.any())).thenCallRealMethod();

        Assert.assertEquals("bart", System.getenv("name"));

        String value = System.getProperty("test-prop");

        Assert.assertEquals("test-value", System.getProperty("test-prop"));
    }
}

I believe this illustrates what you are trying to accomplish. There may be a more elegant way to do this using PowerMockito.spy(), I just can't remember it.

You will need to do thenCallRealMethod() for all the other methods in System.class that get called directly or indirectly by your code.