我正在使用Junit测试委托类。 当我右键单击“运行配置”并将键值对放在“环境”选项卡中时,它可以正常工作。
我尝试从静态块以及@Before方法设置它失败了。 你能帮忙吗?
public MyClass{
public void myMethod(){
String tmp = configProps.getProperty("auto_commit_location");
String commitScriptLocation = System.getenv(tmp);
System.out.println(commitScriptLocation); --- This returns null
}
}
Junit Test:
public class AutoCommitControlDelegateTest {
static {
System.setProperty("auto_commit_location", "/tmp/");
}
@Autowired
private *******
//calls to my methods
答案 0 :(得分:3)
Hmmmm,
我更改了这一行:
String commitScriptLocation = System.getenv(tmp);
到此:
String commitScriptLocation = System.getProperty(tmp);
它有效。 :(我失去了2个小时计算出来。
答案 1 :(得分:2)
要回答您的具体问题,在正在运行的JVM中设置环境变量很复杂(尽管可能:Is it possible to set an environment variable at runtime from Java?)。
相反,如果您能够使用系统属性(What's the difference between a System property and environment variable),那么请考虑使用System Rules("为测试提供系统属性的任意值。测试后,恢复原始值。"):
public void MyTest {
@Rule
public final ProvideSystemProperty myPropertyHasMyValue
= new ProvideSystemProperty("MyProperty", "MyValue");
@Test
public void overrideProperty() {
assertEquals("MyValue", System.getProperty("MyProperty"));
}
}