Skip to content
javahacks.dev
JUnit

JUnit TempDir for Temporary Files and Test Resources

Create and clean up temporary files in JUnit with TempDir, share a directory per class, load files from test resources and avoid fragile paths in tests.

6 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, Jenkins, Cucumber and GitHub Actions logos.

Tests that touch the file system have two classic failures: they leave files behind that break the next run, and they depend on a path that exists on one machine only. JUnit 5 solves the first with @TempDir, which hands the test a fresh directory and deletes it afterwards, and the second needs a discipline about where fixtures come from. This post covers both: the annotation, its three scopes, loading fixture files from the classpath, what cleanup does when it fails, and the places where a temporary directory is not the right tool. It applies to JUnit 5 and 6 on JDK 25.

The basic use

src/test/java/com/example/report/ReportWriterTest.javajava
class ReportWriterTest {

    @TempDir
    Path dir;

    @Test
    void writes_a_csv_file() throws IOException {
        Path out = dir.resolve("report.csv");

        new ReportWriter().write(List.of(new Row("a", 1), new Row("b", 2)), out);

        assertEquals(List.of("name,count", "a,1", "b,2"), Files.readAllLines(out));
    }
}

JUnit creates a new directory under the system temporary location before each test method, injects its Path into the field, and deletes the directory and everything in it after the test. The test writes into dir, passes paths to the code under test, and asserts on the result. There is no @AfterEach, no File.deleteOnExit() and no leftover from a failed run.

The injected type can be Path or File. Prefer Path: it is the modern API, and File exists for code that still takes one. The directory name is random, so never assert on it, and do not rely on the system temp location having a particular layout.

As a parameter

java
@Test
void creates_nested_directories(@TempDir Path dir) throws IOException {
    new Exporter().export(dir.resolve("2026/03"), data);

    assertTrue(Files.isDirectory(dir.resolve("2026/03")));
}

Parameter injection works on test methods and on lifecycle methods such as @BeforeEach. A directory declared on a lifecycle method is shared with the test of that cycle, so a @BeforeEach can fill it with fixtures and the test can read them. Use the parameter form when only one test in the class needs a directory, and the field form when most of them do.

One directory for the class

By default each test gets its own directory. A static field shares one across all tests in the class, created before the first and deleted after the last:

java
class ArchiveIndexTest {

    @TempDir
    static Path shared;

    @BeforeAll
    static void build() throws IOException {
        Files.writeString(shared.resolve("a.txt"), "alpha");
        Files.writeString(shared.resolve("b.txt"), "beta");
    }

    @Test void indexes_all_files() { assertEquals(2, new Indexer().scan(shared).size()); }
    @Test void ignores_hidden_files() { /* ... */ }
}

Sharing saves time when building the fixture is expensive, such as unpacking an archive. The cost is coupling: a test that writes into the shared directory changes the starting state of the next one. Share only directories that tests read, and keep tests that write on their own directory. From JUnit 5.10 you can set @TempDir(cleanup = CleanupMode.ON_SUCCESS) to keep the directory after a failing test, which helps when you want to look at what the code produced; the path is in the failure output if you print it. CleanupMode.NEVER keeps it always, and the default ALWAYS deletes it.

Fixtures from the classpath

Test input files belong in src/test/resources, and the test reads them through the classpath, not through a relative file path:

java
@Test
void parses_the_sample_invoice(@TempDir Path dir) throws IOException {
    try (InputStream in = getClass().getResourceAsStream("/fixtures/invoice.xml")) {
        assertNotNull(in, "fixture is missing from the test classpath");
        Path file = dir.resolve("invoice.xml");
        Files.copy(in, file);

        Invoice invoice = new InvoiceParser().parse(file);

        assertEquals("INV-2026-0042", invoice.number());
    }
}

A path like "src/test/resources/fixtures/invoice.xml" works when the working directory is the module root and fails in the IDE, in a multi-module build, or when tests run from a packaged jar. The classpath lookup works everywhere. The assertNotNull on the stream turns a typo in the name from a NullPointerException into a message that names the problem; see fixing NullPointerException for how to read the unhelpful kind.

Copy the fixture into the temporary directory when the code under test needs a real file, or modifies it. Do not write into src/test/resources. It is read-only in packaged builds, shared across tests, and under version control, so a test that edits a fixture changes it for everybody and shows up in git status.

Cleanup behaviour

JUnit deletes the directory recursively after the test. If deletion fails, because a file is still open or a permission was changed, the test fails with an IOException that names the path. On Windows, an open handle prevents deletion, and the fix is to close the stream or channel your code opened, usually with try-with-resources. A test that makes a file read-only to test an error path leaves a directory that the cleanup cannot remove on some platforms; restore the permission in a finally.

If the production code starts a thread that keeps writing into the directory after the test returns, cleanup races with it and fails randomly. Wait for the thread, or make the code under test synchronous in tests.

Spring and Maven

In a Spring test the temporary path can be fed into configuration with a @DynamicPropertySource, so the application writes to the test directory:

java
@TempDir static Path uploads;

@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
    registry.add("app.upload-dir", () -> uploads.toString());
}

The directory must be static here, because the registry is read before the instance exists. Maven and Gradle set the working directory to the module root, so relative paths resolve against it, but that is the assumption this post argues against. Put generated output under target/ or build/ only for artifacts you want to inspect, never as test scratch space.

The directory lives in the platform's temporary location, which is a short path on Linux and a long one under the user profile on Windows. Code that builds absolute paths of more than 260 characters can fail there while it passes on Linux; keep the fixture tree shallow. Tests that need symbolic links or POSIX permissions should be guarded with @DisabledOnOs(OS.WINDOWS) or an assumption, since creating a symlink on Windows needs a privilege that CI agents often lack. The temporary directory is also on a different file system from the project in most setups, so tests of "move a file" behave differently from tests that stay within one volume, and an atomic rename across volumes fails. If the code under test uses Files.move with ATOMIC_MOVE, create the source and target inside the same @TempDir.

Finally, keep file names in tests deterministic. Generating names from a clock or a random number makes a failure harder to reproduce, because the name in the log never recurs. Use fixed names inside the unique directory, which is already unique enough.

When a real directory is the wrong tool

A temporary directory touches the actual disk. For code that only needs a file system abstraction, an in-memory implementation such as Jimfs is faster and works the same across operating systems, and it can simulate Windows paths on Linux. It requires the code under test to accept a Path or a FileSystem rather than build File objects itself. For tests of file-handling logic, test doubles are an alternative, compared in mocks, stubs and fakes. The extension is documented in the JUnit user guide, and Jimfs lives at google/jimfs. More of the framework is in the JUnit 5 handbook.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.