如果您将user.dir 设置为系统属性,那么除非您将其删除,否则它将在该JVM 的生命周期内一直存在。因此,您必须为每个测试生成一个新的 JVM,或者以某种方式管理测试用例之间的系统属性。您可以使用JUnit Rule 轻松设置/取消设置系统属性。
这是一个例子:
public class SystemPropertyRule extends ExternalResource {
private final Map<String, String> properties = new LinkedHashMap<String, String>();
private final Map<String, String> restoreProperties = new LinkedHashMap<String, String>();
public SystemPropertyRule(String propertyName, String propertyValue) {
this.properties.put(propertyName, propertyValue);
}
@Override
protected void before() throws Throwable {
for (Map.Entry<String, String> entry : properties.entrySet()) {
String propertyName = entry.getKey();
String propertyValue = entry.getValue();
String existingValue = System.getProperty(propertyName);
if (existingValue != null) {
// store the overriden value so that it can be reinstated when the test completes
restoreProperties.put(propertyName, existingValue);
}
System.setProperty(propertyName, propertyValue);
}
}
@Override
protected void after() {
for (Map.Entry<String, String> entry : properties.entrySet()) {
String propertyName = entry.getKey();
String propertyValue = entry.getValue();
if (restoreProperties.containsKey(propertyName)) {
// reinstate the overridden value
System.setProperty(propertyName, propertyValue);
} else {
// remove the (previously unset) property
System.clearProperty(propertyName);
}
}
}
}
你可以像这样在你的测试用例中使用它:
@ClassRule
public static final SystemPropertyRule systemPropertyRule = new SystemPropertyRule("foo", "bar");
@Test
public void testPropertyIsSet() {
Assert.assertEquals("bar", System.getProperty("foo"));
}
此规则将包装测试用例调用,并添加以下行为:
- 之前:使用给定值设置命名系统属性
- 之后:丢弃该属性(如果在运行此测试用例之前未设置)或恢复该属性的先前值(如果该属性在运行测试用例之前有值)
使用此规则,您可以控制为每个测试设置 user.dir(允许对其进行设置/取消设置/恢复等),尽管它最终确实相当于为每个测试调用 user.dir=...,但它不是很具有侵入性,并且它使用了专门用于此目的的 JUnit 机制。