在junit中模拟System.getenv调用时遇到麻烦

PCR*_*PCR 5 java junit unit-testing

我正在尝试为Spring Boot应用程序使用junit和mockito(对此非常新)编写单元测试。基本上,在我的代码中,我为manifest.yml文件(用于部署)中的特定URL指定了一个环境变量,可以String URL = System.getenv("VARIABLE")在我的代码中访问该变量。但是,由于URL变量显然未定义,因此我在单元测试中遇到了很多麻烦。我在这里尝试了该解决方案,但是意识到这仅用于模拟环境变量(如果您从实际测试本身调用它),而不是如果您依赖于可从代码访问的环境变量。

有什么方法可以设置它,以便在运行测试时可以设置可以在代码中访问的环境变量?

Stv*_*dll 5

您可以PowerMockito用来模拟静态方法。此代码演示了模拟System类和存根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"));
        Assert.assertEquals("test-value", System.getProperty("test-prop"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信这说明了您正在努力实现的目标。有可能是一个更优雅的方式来做到这一点使用PowerMockito.spy(),我只是不记得了。

您将需要对thenCallRealMethod()System.class 中由您的代码直接或间接调用的所有其他方法进行处理。