Note
Since JUnit Jupiter 5.4, there’s a built-in @TempDir extension. It doesn’t support custom file systems, but other than that it’s much better than this version, so we removed the extension in JUnit Pioneer 1.0. We plan to tackle this problem again in the future - see issue #348.

The TempDirectory extension can be used to create and clean up a temporary directory for an individual test or all tests in a test class. To use it, simply register the extension and add a parameter of type java.nio.file.Path to your test or lifecycle method or constructor.

For example, the following test registers the extension for a single test method, creates and writes a file to the temporary directory and checks its content.

@Test
@ExtendWith(TempDirectory.class)
void test(@TempDir Path tempDir) {
    Path file = tempDir.resolve("test.txt");
    writeFile(file);
    assertExpectedFileContent(file);
}

In addition to the default file system, the extension can be used with any FileSystem implementation, e.g. Jimfs. In order to use a custom file system, simply register the extension programmatically and pass a provider of a custom parent directory of type Path. The following example uses the Jimfs FileSystem and passes a custom tmp parent directory to the static factory method TempDirectory::createInCustomDirectory.

class MyTests {

    private static FileSystem fileSystem;

    @BeforeAll
    static void createFileSystem() {
        fileSystem = Jimfs.newFileSystem();
    }

    @AfterAll
    static void closeFileSystem() throws Exception {
        fileSystem.close();
    }

    @RegisterExtension
    Extension tempDirectory = TempDirectory.createInCustomDirectory(() ->
        Files.createDirectories(fileSystem.getPath("tmp")));

    @Test
    void test(@TempDir Path tempDir) {
        Path file = tempDir.resolve("test.txt");
        writeFile(file);
        assertExpectedFileContent(file);
    }

}

Thread-Safety

This extension’s thread-safety is undetermined, we recommend to be cautious when using it during parallel test execution. (We’re working on it.)