我有一段Java代码,它使用了一个环境变量,代码的行为取决于这个变量的值。我想用不同的环境变量值来测试这段代码。我如何在JUnit中做到这一点?
我大体上看过some ways to set environment variables in Java,但我对它的单元测试方面更感兴趣,特别是考虑到测试不应该相互干扰。
发布于 2016-02-14 23:42:54
库System Lambda有一个用于设置环境变量的方法withEnvironmentVariables
。
import static com.github.stefanbirkner.systemlambda.SystemLambda.*;
public void EnvironmentVariablesTest {
@Test
public void setEnvironmentVariable() {
String value = withEnvironmentVariable("name", "value")
.execute(() -> System.getenv("name"));
assertEquals("value", value);
}
}
对于Java5到7,库System Rules有一个名为EnvironmentVariables
的JUnit规则。
import org.junit.contrib.java.lang.system.EnvironmentVariables;
public class EnvironmentVariablesTest {
@Rule
public final EnvironmentVariables environmentVariables
= new EnvironmentVariables();
@Test
public void setEnvironmentVariable() {
environmentVariables.set("name", "value");
assertEquals("value", System.getenv("name"));
}
}
完全公开:我是这两个库的作者。
发布于 2011-11-17 22:44:03
通常的解决方案是创建一个类来管理对此环境变量的访问,然后可以在测试类中模拟该环境变量。
public class Environment {
public String getVariable() {
return System.getenv(); // or whatever
}
}
public class ServiceTest {
private static class MockEnvironment {
public String getVariable() {
return "foobar";
}
}
@Test public void testService() {
service.doSomething(new MockEnvironment());
}
}
然后,测试中的类使用environment类获取环境变量,而不是直接从System.getenv()获取。
发布于 2015-06-24 22:54:32
我认为最干净的方法是使用Mockito.spy()。这比创建一个单独的类来模拟和传递要轻量级一些。
将您的环境变量获取移动到另一个方法:
@VisibleForTesting
String getEnvironmentVariable(String envVar) {
return System.getenv(envVar);
}
现在,在您的单元测试中执行以下操作:
@Test
public void test() {
ClassToTest classToTest = new ClassToTest();
ClassToTest classToTestSpy = Mockito.spy(classToTest);
Mockito.when(classToTestSpy.getEnvironmentVariable("key")).thenReturn("value");
// Now test the method that uses getEnvironmentVariable
assertEquals("changedvalue", classToTestSpy.methodToTest());
}
https://stackoverflow.com/questions/8168884
复制相似问题