在eclipse / Junit中有多个测试如何检索初始默认目录

时间:2017-08-11 10:03:45

标签: java eclipse junit directory

当我使用junit执行一次测试时,我可以通过设置user.dir来查找当前目录中的文件,即启动目录,或者将其改为相对。 / p>

但是当我启动多个测试时,user.dir仍在测试之间,如果我之前设置它,那就太乱了。

每个测试如何获得初始默认目录,即使它已被先前的测试更改,也不设置每个测试配置(-Duser.dir ...)

感谢GhostCat,这是一个简短的解决方案:

static String user_dir_initial="";  
@Before
       public void before()
        {
    if (user_dir_initial.contentEquals(""))
        user_dir_initial=System.getProperty("user.dir");
        System.out.println("USER DIR INITIAL:"+user_dir_initial);
        System.setProperty("user.dir", user_dir_initial);
        }

2 个答案:

答案 0 :(得分:1)

如果将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机制,用于此目的。

答案 1 :(得分:1)

如果要确保为所有测试用例设置某个属性,可以将@Before或@BeforeClass注释与System.setProperty()一起使用到强制某个设置。

如果你必须撤消,你可以以对称的方式使用@After或@AfterClass!