A fresh folder for every test

A test that writes a file needs a place to write it, and the place must be empty, unique and easy to remove. @TempDir gives the test a folder the framework creates before and deletes after, one per test, so two tests never share a file by accident. The article Temporary folders in tests is the short version.

@TempDir

The annotation goes on a field of type Path or File, or on a parameter of a test or lifecycle method. Jupiter creates the folder before the test and deletes it after the class, including the files inside it. The name is a random one under the system temporary directory.

A field and a parameter

A field is the simple form when every test of the class needs a folder; each test gets its own. A parameter puts the folder in the signature of the one test that needs it, which keeps the class free of a field only one test reads. The two forms may be mixed.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; public class TempTest { @TempDir Path folder; @Test void folderIsADirectory() { assertTrue(Files.isDirectory(folder)); } @Test void writesAFile() throws Exception { Path file = folder.resolve("note.txt"); Files.writeString(file, "hello"); assertEquals("hello", Files.readString(file)); } }

Two tests and two folders

The field looks shared, but Jupiter fills it before each test with a new folder. The second test does not see the note.txt of the first, even though both use the same field name. That is the property the annotation exists for: isolation without a cleanup method in the test.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out TempTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ TempTest ✔
│     ├─ writesAFile() ✔
│     └─ folderIsADirectory() ✔
└─ JUnit Vintage ✔

Test run finished after 840 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

The cleanup

Jupiter deletes the folder after the class, not after each test, so a file a test leaves behind is visible to the next test if the next test looks outside its own folder. The isolation comes from the new folder, not from the deletion; do not rely on the old one disappearing between tests.

The annotation needs a writable temporary directory. In this image that is /tmp, and the wrapper runs the tests in a container where it exists. A test that must keep a file for a manual look can copy it out before the class ends; the report does not show the path, so a debugging test usually prints it.

Exercises

  1. Add a parameter @TempDir Path other to one test and print both paths. Are they the same folder?
  2. Write a file in one test and try to read it by name in the other. What does the second test get?
  3. Replace the field with a parameter on both tests. Does the report change?
  4. Use @TempDir File folder instead of Path and change the file calls to the File API.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many temporary folders does a class with two tests and a @TempDir field get?

    Answer

    Two, one for each test

    The field is filled with a new folder before every test.

  2. Where can @TempDir be placed?

    Answer

    On a field or on a parameter

    The annotation supports a field of Path or File and a parameter of a test or lifecycle method.

  3. When does Jupiter delete the folder?

    Answer

    After the class

    The folder is removed at the end of the class; a new one was already made for each test.

  4. What does this program print? public class Q1 { public static void main(String[] args) { java.nio.file.Path path = java.nio.file.Path.of("a", "b"); System.out.println(path); } }

    Answer

    a/b

    Path.of joins the names with the platform separator, a slash on Linux.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println("note.txt".endsWith(".txt")); } }

    Answer

    true

    The name ends with .txt, so the check is true.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String text = "hello"; System.out.println(text.length()); } }

    Answer

    5

    The word has five letters.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println(java.nio.file.Path.of("x").toAbsolutePath().isAbsolute()); } }

    Answer

    true

    toAbsolutePath makes the path absolute, so isAbsolute is true.

  8. Why does a new folder per test matter?

    Answer

    One test cannot see or overwrite the files of another

    Isolation is the point: each test starts with an empty folder of its own.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(java.nio.file.Path.of("a", "b").getFileName()); } }

    Answer

    b

    getFileName returns the last element of the path, b.

  10. A test leaves a file in the folder and the class ends. What happens to it?

    Answer

    Jupiter deletes the folder with the file when the class ends

    The temporary folder is removed at the end of the class, files included.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image