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);
    }
}

Updated: