我正在尝试使用 junit 和mockito(对此非常新)为 Spring Boot 应用程序编写单元测试。基本上在我的代码中,我已经为 manifest.yml 文件(用于部署)中的特定 URL 指定了一个环境变量,我可以通过它访问String URL = System.getenv("VARIABLE")
在我的代码中。然而,我的单元测试遇到了很多麻烦,因为URL
变量显然是未定义的。我尝试了解决方案here https://stackoverflow.com/questions/8168884/how-to-test-code-dependent-on-environment-variables-using-junit/8169008,但意识到这仅适用于模拟环境变量(如果您是从实际测试本身调用它),而不是如果您依赖于可从代码访问的环境变量。
有什么方法可以设置它,以便在运行测试时,我可以设置可以在代码中访问的环境变量?
您可以使用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"));
}
}
我相信这说明了您正在努力实现的目标。
那里may使用 PowerMockito.spy() 是一种更优雅的方法,我只是不记得了。
你需要做thenCallRealMethod()
对于 System.class 中由代码直接或间接调用的所有其他方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)