Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't JUnit TemporaryFolder deleted?

Tags:

java

junit

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?

like image 765
jveldridge Avatar asked May 11 '13 06:05

jveldridge


1 Answers

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
like image 179
Evgeniy Dorofeev Avatar answered Sep 20 '22 06:09

Evgeniy Dorofeev