Temporary folders in tests

A test that writes a file needs a folder it may write to, and it needs the folder to be empty when the test starts and gone when the run ends. Writing into the project folder leaves files behind and makes two runs interfere; writing into a fixed name under the system temporary folder has the same problem with two runs at once. @TempDir is the answer: the framework makes a folder for the test, hands it over, and deletes it afterwards.

The code that writes

A ledger of lines, each a number and a word, with an append, a read and a total. The methods take the path, so the caller decides where the file goes; that is what makes the same code usable by a program, which writes next to itself, and by a test, which writes into a folder of its own:

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; public class Ledger { static void append(Path file, String line) throws IOException { Files.writeString(file, line + "\n", StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND); } static List<String> read(Path file) throws IOException { return Files.readAllLines(file, StandardCharsets.UTF_8); } static int total(List<String> lines) { int sum = 0; for (String line : lines) { sum += Integer.parseInt(line.split(" ", 2)[0]); } return sum; } public static void main(String[] args) throws IOException { Path file = Path.of("ledger.txt"); append(file, "10 coffee"); append(file, "-4 tea"); List<String> lines = read(file); System.out.println("lines: " + lines); System.out.println("total: " + total(lines)); Files.delete(file); } }

The program writes ledger.txt in the folder it runs in and deletes it at the end, which is the right behaviour for a demonstration and the wrong one for a test: a run that fails between the write and the delete leaves the file for the next run, and two runs at once write into the same file. The tests below never touch that name.

@TempDir on a field

The annotation on an instance field of type Path or File makes the framework fill it before each test. The field is assigned after the test object is made and before @BeforeEach, so a setup method sees the folder as well. Three tests below use it in three ways: write and read a file, check that the folder starts empty, and take a second folder as a parameter:

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.io.TempDir; @TestMethodOrder(MethodOrderer.MethodName.class) public class LedgerTest { @TempDir Path dir; @Test void writesAndReadsTwoLines() throws IOException { Path file = dir.resolve("ledger.txt"); Ledger.append(file, "10 coffee"); Ledger.append(file, "-4 tea"); List<String> lines = Ledger.read(file); assertEquals(2, lines.size()); assertEquals("10 coffee", lines.get(0)); assertEquals(6, Ledger.total(lines)); } @Test void startsInAnEmptyFolder() throws IOException { assertFalse(Files.exists(dir.resolve("ledger.txt"))); try (var entries = Files.list(dir)) { assertEquals(0, entries.count()); } } @Test void takesAFolderAsAParameter(@TempDir Path own) throws IOException { Path file = own.resolve("one.txt"); Ledger.append(file, "1 item"); assertTrue(Files.size(file) > 0); assertEquals("1 item", Ledger.read(file).get(0)); } }

A folder per test

The second test is the one that proves the first is isolated: it asserts that ledger.txt does not exist and that the folder is empty, although the first test wrote a file into a folder of that name. The field is filled again for every test, so the folder of the first test is already gone when the second starts.

The order of the report shows why. startsInAnEmptyFolder runs first, alphabetically, and sees an empty folder; the write test runs after it and does not care. A test that depends on the order would be a broken test, and the fresh folder is what makes the order irrelevant.

@TempDir on a parameter

The third test takes its folder as a parameter instead of using the field, which is the form to prefer when only one method needs a folder: the dependency is in the signature and a reader does not have to look at the fields. Both forms are resolved by the same extension, and a class may mix them, as this one does.

The run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Ledger.java LedgerTest.java
java -cp out Ledger

lines: [10 coffee, -4 tea]
total: 6

junit execute --class-path out --select-class LedgerTest --disable-ansi-colors

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

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ LedgerTest ✔
│ ├─ startsInAnEmptyFolder() ✔
│ ├─ takesAFolderAsAParameter(Path) ✔
│ └─ writesAndReadsTwoLines() ✔
└─ JUnit Vintage ✔

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

Where the folder is and when it goes

The folder is made under the system temporary folder, which java.io.tmpdir names, with a name of the framework's choosing, so two runs never share one. The default cleanup is ALWAYS: the folder is deleted after the test, whether it passed or failed. @TempDir(cleanup = CleanupMode.ON_SUCCESS) keeps the folder of a failed test, which is what a person debugging a file bug wants to look at.

The folder is deleted recursively, so a test may make subfolders inside it. It is not a sandbox and it is not cleaned while the test runs: the test owns it from the moment it is injected, and a test that opens a file and forgets to close it may stop the deletion on Windows, which is one more reason to use the try-with-resources of lesson 098.

What comes next

Every page so far has put its sources in one folder and named every file on the command line. A project of any size separates the code from the tests and compiles each into its own output folder. The next page is that layout, with the two javac runs and the class path the launcher needs to see both.

The Java course covers the files themselves from lesson 106, the try-with-resources that closes a directory stream in lesson 098, and the temporary file API of the JDK in lesson 107.

The code on this page was compiled with OpenJDK 21.0.13 (javac) and run with the JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container. The time in the report is that machine's and changes between runs.

Article author: Arthur Isaev