Why isn't JUnit TemporaryFolder deleted?

霸气de小男生 提交于 2020-12-29 09:02:24

问题


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)"

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.

Why is this not getting deleted?


回答1:


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() {
    }
}

output

true
false


来源:https://stackoverflow.com/questions/16494459/why-isnt-junit-temporaryfolder-deleted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!