我正在尝试为Spring Boot应用程序使用junit和mockito(这是新的)编写一个单元测试。基本上,在我的代码中,我已经为manifest.yml文件(用于部署)中的特定URL指定了一个环境变量,我可以通过代码中的String URL = System.getenv("VARIABLE")
对其进行访问。但是,由于URL
变量显然是未定义的,因此我在单元测试中遇到了很多麻烦。我尝试了解决方案here,但是意识到这仅用于模拟环境变量(如果您从实际测试本身调用它),而不是如果您依赖于可从代码访问的环境变量。
有什么方法可以设置它,以便在运行测试时可以设置可以在代码中访问的环境变量?
最佳答案
您可以使用PowerMockito
模拟静态方法。此代码演示了如何模拟System
类和对getenv()
进行 stub
@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()可能有一种更优雅的方式来执行此操作,我只是不记得了。
您将需要对System.class中所有其他直接或间接被代码调用的方法执行
thenCallRealMethod()
。