Search code examples
javajunit

Why isn't JUnit TemporaryFolder deleted?


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?


Solution

  • 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