如何使用 JUnit 测试依赖于环境变量的代码? [英] How to test code dependent on environment variables using JUnit?
问题描述
我有一段使用环境变量的 Java 代码,代码的行为取决于该变量的值.我想用不同的环境变量值来测试这段代码.我如何在 JUnit 中执行此操作?
I have a piece of Java code which uses an environment variable and the behaviour of the code depends on the value of this variable. I would like to test this code with different values of the environment variable. How can I do this in JUnit?
我已经看到了一些在 Java 中设置环境变量的方法 一般而言,但我对它的单元测试方面更感兴趣,尤其是考虑到测试不应相互干扰.
I've seen some ways to set environment variables in Java in general, but I'm more interested in unit testing aspect of it, especially considering that tests shouldn't interfere with each other.
推荐答案
库 System Lambda 有一个方法 withEnvironmentVariables
用于设置环境变量.
The library System Lambda has a method withEnvironmentVariables
for setting environment variables.
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);
}
}
对于 Java 5 到 7,库系统规则 有一个名为 的 JUnit 规则环境变量
.
For Java 5 to 7 the library System Rules has a JUnit rule called EnvironmentVariables
.
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"));
}
}
完全公开:我是这两个库的作者.
Full disclosure: I'm the author of both libraries.
这篇关于如何使用 JUnit 测试依赖于环境变量的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!