Sub topic 13
Testing File Code with @TempDir
Many programs read and write files. A notes app saves notes. A report tool writes a CSV file. You need to test that code too. Tests that use real files have their own problems, though. This chapter shows how JUnit's @TempDir handles them.
Why real files cause trouble in tests
Suppose a test writes to C:\notes\test.txt or /home/sam/notes/test.txt. Several things can go wrong:
- Leftover files. If the test crashes, the file stays on disk. The next run may see old data and pass or fail for the wrong reason.
- Shared folders. Two tests that use the same folder can overwrite each other's files.
- Machine differences. A path that exists on your laptop may not exist on a teammate's computer or on the build server.
- Damage. A bug in the test could delete or change real project files.
A good unit test is repeatable. That means it gives the same result every time, on every machine. Real file paths break that rule.
What @TempDir does
A temporary directory is a folder made for short-term use, usually inside the operating system's temp area. @TempDir is a JUnit annotation that asks JUnit to create a fresh temporary directory for you. JUnit passes the folder to your test, and it deletes the folder and everything inside it when the test is done.
You do not write any setup or cleanup code yourself. JUnit does both.
@TempDir lives in the package org.junit.jupiter.api.io. It comes with the junit-jupiter dependency you added earlier, so you need nothing extra.
The simplest example
Here is the smallest useful test. It puts @TempDir on a field. A field is a variable that belongs to the class.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class FileWritingTest {
@TempDir
Path tempDir;
@Test
void writesAndReadsFile() throws IOException {
Path file = tempDir.resolve("note.txt");
Files.writeString(file, "hello");
assertEquals("hello", Files.readString(file));
}
}Here is what each part does:
Pathis Java's type for a location on disk. JUnit fills intempDirbefore the test runs.tempDir.resolve("note.txt")builds a path to a file inside the temp folder. The file does not exist yet.Files.writeStringcreates the file and writes text into it.Files.readStringreads the text back, andassertEqualschecks it.
The field must not be final or private. JUnit has to be able to set it, so leave it package-private as shown.
A realistic class under test
Real code usually takes a folder from outside rather than hard-coding one. This class saves and loads notes in whatever folder you give it.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NoteStore {
private final Path folder;
public NoteStore(Path folder) {
this.folder = folder;
}
public Path save(String name, String text) throws IOException {
if (name.isBlank()) {
throw new IllegalArgumentException("name must not be blank");
}
Path file = folder.resolve(name + ".txt");
Files.writeString(file, text);
return file;
}
public String load(String name) throws IOException {
return Files.readString(folder.resolve(name + ".txt"));
}
public List<String> listNames() throws IOException {
try (Stream<Path> files = Files.list(folder)) {
return files
.map(p -> p.getFileName().toString())
.filter(n -> n.endsWith(".txt"))
.map(n -> n.substring(0, n.length() - 4))
.sorted()
.collect(Collectors.toList());
}
}
}The constructor takes a Path, so a test can hand it a temp folder and the app can hand it a real one. This design choice is called passing in a dependency. It makes code much easier to test.
Testing NoteStore
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class NoteStoreTest {
@TempDir
Path folder;
private NoteStore store;
@BeforeEach
void setUp() {
store = new NoteStore(folder);
}
@Test
void saveCreatesFileInFolder() throws IOException {
Path file = store.save("shopping", "milk");
assertTrue(Files.exists(file));
assertEquals(folder, file.getParent());
}
@Test
void loadReturnsSavedText() throws IOException {
store.save("todo", "call mom");
assertEquals("call mom", store.load("todo"));
}
@Test
void newFolderStartsEmpty() throws IOException {
assertEquals(List.of(), store.listNames());
}
@Test
void listNamesReturnsSortedNames() throws IOException {
store.save("b", "two");
store.save("a", "one");
assertEquals(List.of("a", "b"), store.listNames());
}
@Test
void loadingMissingNoteThrows() {
assertThrows(NoSuchFileException.class, () -> store.load("ghost"));
}
}Look at newFolderStartsEmpty. It passes even if listNamesReturnsSortedNames ran first. JUnit gives each test its own new, empty folder, so no test can see another test's files. That keeps the tests independent: each one works no matter the order they run in.
The @BeforeEach method can use folder because JUnit fills in @TempDir fields before any @BeforeEach method runs.
Using @TempDir as a parameter
You can also ask for the folder as a method parameter. This keeps the folder local to one test.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class NoteStoreParameterTest {
@Test
void overwritingReplacesText(@TempDir Path dir) throws IOException {
NoteStore store = new NoteStore(dir);
store.save("plan", "first");
store.save("plan", "second");
assertEquals("second", store.load("plan"));
}
}Use a field when most tests in the class need a folder. Use a parameter when only one or two do.
Field, parameter, or static field?
| Where you put @TempDir | Folder is shared by | When to use it |
|---|---|---|
| Instance field | One test method (new folder each test) | Most tests in the class use files |
| Test method parameter | That one test method | Only a few tests need a folder |
| `static` field | All tests in the class | Expensive setup that every test only reads |
A static field gives one folder for the whole class. JUnit deletes it after the last test. Be careful here, because tests that write into a shared folder can affect each other again.
Edge cases and common mistakes
- Using a plain String path.
@TempDirworks withPathorjava.io.File. PreferPath, since it is the modern API. - Assigning the field yourself. Writing
Path folder = Path.of("x");with@TempDircauses an error. Let JUnit set it. - Open files on Windows. Windows cannot delete a file that is still open. If your code opens a stream and never closes it, cleanup may fail. Use try-with-resources, as
listNamesdoes withFiles.list. - Subfolders. You can create them freely with
Files.createDirectories(folder.resolve("a/b")). JUnit deletes them too. - Checking a file after a failure. By default JUnit always deletes the folder. To keep it when a test fails, write
@TempDir(cleanup = CleanupMode.ON_SUCCESS)and importorg.junit.jupiter.api.io.CleanupMode. This needs JUnit 5.9 or later.
Summary
@TempDirgives each test a fresh, empty folder and deletes it afterward.- Put it on an instance field, on a method parameter, or on a static field to share one folder.
- Design file code to accept a
Path, so tests can pass in the temp folder. - Close your streams so cleanup works on every operating system.
Exercise
You have two tests in one class. Both use an instance field annotated with @TempDir. Test A saves "x.txt". Test B checks that the folder has no files. Will Test B pass if Test A runs first? Why?
Show answer
Yes. With an instance field, JUnit creates a new, empty temporary directory for each test method and deletes it afterward. Test B gets its own folder, so it never sees x.txt from Test A.
Exercise
Write a test for NoteStore that checks save throws IllegalArgumentException with the message "name must not be blank" when the name is " ". Use @TempDir as a method parameter.
Show answer
@Test void blankNameThrows(@TempDir Path dir) { NoteStore store = new NoteStore(dir); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> store.save(" ", "text")); assertEquals("name must not be blank", ex.getMessage()); } The test also needs imports for Test, TempDir, Path, assertThrows, and assertEquals.
Exercise
A test on Windows fails during cleanup with an error saying a file in the temp folder could not be deleted. What is the most likely cause in the code under test?
Show answer
The code opened a file or directory stream and never closed it. Windows will not delete an open file. Wrap the stream in try-with-resources so it closes before the test ends.