本文介绍了在junit中模拟System.getenv调用时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以使用PowerMockito模拟静态方法.这段代码演示了模拟System类和对getenv()

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"));
    }
}

我相信这可以说明您正在努力实现的目标.使用PowerMockito.spy()可能有一种一种更优雅的方法来完成此操作,我只是不记得了.

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.

对于在代码中直接或间接调用的System.class中的所有其他方法,您将需要执行thenCallRealMethod().

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

这篇关于在junit中模拟System.getenv调用时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:22