为什么不删除JUnit TemporaryFolder? [英] Why isn't JUnit TemporaryFolder deleted?
问题描述
JUnit的TemporaryFolder规则的文档指出,它创建了
The documentation for JUnit's TemporaryFolder rule states that it creates files and folders that are
"保证在测试方法完成后删除(无论是否 通过或失败)"
"guaranteed to be deleted when the test method finishes (whether it passes or fails)"
但是,断言TemporaryFolder不存在会失败:
However, asserting that the TemporaryFolder does not exist fails:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class MyTest {
@Rule
public TemporaryFolder _tempFolder = new TemporaryFolder();
@After
public void after() {
assertFalse(_tempFolder.getRoot().exists()); //this assertion fails!
}
@Test
public void pass() throws IOException {
assertTrue(true);
}
我还看到文件确实存在于文件系统上.
I also see that the file indeed exists on the file system.
为什么不删除它?
推荐答案
这是因为JUnit在删除临时文件夹之前先调用after().您可以尝试在@AfterClass方法中检查temp文件夹,然后将其删除.该测试证明了这一点
This is because JUnit calls after() before it removed the temp folder. You can try to check temp folder in an @AfterClass method and you will see it's removed. This test proves it
public class MyTest {
static TemporaryFolder _tempFolder2;
@Rule
public TemporaryFolder _tempFolder = new TemporaryFolder();
@After
public void after() {
_tempFolder2 = _tempFolder;
System.out.println(_tempFolder2.getRoot().exists());
}
@AfterClass
public static void afterClass() {
System.out.println(_tempFolder2.getRoot().exists());
}
@Test
public void pass() {
}
}
输出
true
false
这篇关于为什么不删除JUnit TemporaryFolder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!