Why isn't JUnit TemporaryFolder deleted?
Asked Answered
E

2

18

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?

Earthiness answered 11/5, 2013 at 6:24 Comment(1)
The temp folder will be not deleted if there is a lock (e.g. not closed OutputStream) on any file within the temp folder.Starflower
F
12

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
Fee answered 11/5, 2013 at 6:36 Comment(2)
I have the same issue, I test it in the AfterClass , and it doesn't delete there either , I tried closing all open streams, What else can be causing the temporary files and folder to not be deletedMarjoriemarjory
I have tried creating an @AfterClass method to check the existence and then I manually try to delete the folder but it won't. The files being created are gone but the original junit folder is not goneGroats
C
3

I stumbled upon this question facing the same issue and in my case the cause of the missing deletion was an improper use of the temporary folder.

The toString() method returns the internal folder name, so when trying to create a new file within it, JUnit creates a new folder within the project root. Adding the getRoot() method solved the issue.

Here's the code I blame:

@Rule
public TemporaryFolder projectFolder = new TemporaryFolder();
//some lines later...
FileUtils.copyFile(deployFile, new File(projectFolder + "/deploy.xml"));
//how I fixed it
FileUtils.copyFile(deployFile, new File(projectFolder.getRoot() + "/deploy.xml"));
Cruciate answered 29/6, 2021 at 15:40 Comment(1)
Thankyou for saving my rest of the daySouthernly

© 2022 - 2024 — McMap. All rights reserved.