如何根据使用JUnit的环境变量来测试代码? [英] How to test code dependent on environment variables using JUnit?
问题描述
我看过在Java中设置环境变量的一些方法,但是我对单元测试方面更感兴趣,特别是考虑到测试不应该相互干扰
通常的解决方案是创建一个管理对这个环境变量的访问权限的类,然后你可以嘲笑你的测试类。
public class Environment {
public String getVariable(){
return System.getenv ); //或任何
}
}
public class ServiceTest {
private static class MockEnvironment {
public String getVariable(){
return FOOBAR;
}
}
@Test public void testService(){
service.doSomething(new MockEnvironment());
}
}
测试中的类然后使用环境类,不直接来自System.getenv()。
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?
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.
The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.
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());
}
}
The class under test then gets the environment variable using the Environment class, not directly from System.getenv().
这篇关于如何根据使用JUnit的环境变量来测试代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!