2.20. Built-in Extensions
While the JUnit team encourages reusable extensions to be packaged and maintained in separate libraries, the JUnit Jupiter API artifact includes a few user-facing extension implementations that are considered so generally useful that users shouldn’t have to add another dependency.
2.20.1. The TempDirectory Extension
@TempDir is an experimental feature |
The built-in [TempDirectory](https://github.com/junit-team/junit5/tree/r5.7.0/junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/TempDirectory.java)
extension is used to create and clean up a temporary directory for an individual test or all tests in a test class. It is registered by default. To use it, annotate a non-private field of type java.nio.file.Path
or java.io.File
with [@TempDir](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/io/TempDir.html)
or add a parameter of type java.nio.file.Path
or java.io.File
annotated with @TempDir
to a lifecycle method or test method.
For example, the following test declares a parameter annotated with @TempDir
for a single test method, creates and writes to a file in the temporary directory, and checks its content.
A test method that requires a temporary directory
@Test
void writeItemsToFile(@TempDir Path tempDir) throws IOException {
Path file = tempDir.resolve("test.txt");
new ListWriter(file).write("a", "b", "c");
assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
}
@TempDir is not supported on constructor parameters. If you wish to retain a single reference to a temp directory across lifecycle methods and the current test method, please use field injection, by annotating a non-private instance field with @TempDir . |
The following example stores a shared temporary directory in a static
field. This allows the same sharedTempDir
to be used in all lifecycle methods and test methods of the test class.
A test class that shares a temporary directory across test methods
class SharedTempDirectoryDemo {
@TempDir
static Path sharedTempDir;
@Test
void writeItemsToFile() throws IOException {
Path file = sharedTempDir.resolve("test.txt");
new ListWriter(file).write("a", "b", "c");
assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
}
@Test
void anotherTestThatUsesTheSameTempDir() {
// use sharedTempDir
}
}