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
You’re invited to give it a try and provide feedback to the JUnit team so they can improve and eventually promote this 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

  1. @Test
  2. void writeItemsToFile(@TempDir Path tempDir) throws IOException {
  3. Path file = tempDir.resolve("test.txt");
  4. new ListWriter(file).write("a", "b", "c");
  5. assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
  6. }
@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

  1. class SharedTempDirectoryDemo {
  2. @TempDir
  3. static Path sharedTempDir;
  4. @Test
  5. void writeItemsToFile() throws IOException {
  6. Path file = sharedTempDir.resolve("test.txt");
  7. new ListWriter(file).write("a", "b", "c");
  8. assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
  9. }
  10. @Test
  11. void anotherTestThatUsesTheSameTempDir() {
  12. // use sharedTempDir
  13. }
  14. }