Saturday, March 06, 2021

Creating Temporary Files with JUnit 5

This post shows you how to perform unit testing using temporary files with JUnit 5. If you're still on JUnit 4, please check out my previous post!

In JUnit 5, the @TempDir annotation is used to indicate that a field or method parameter of type Path or File is a temporary directory. Each test will use its own temporary directory and when the test method has finished executing, the directory and all its contents will be deleted. (If you want to share a temporary directory between tests, you need to make the field static.)

Here is an example:

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;

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;

public class MyTest {

  @TempDir
  Path tempDir;

  @Test
  public void testWrite() throws IOException {

    // Create a temporary file.
    // This is guaranteed to be deleted after the test finishes.
    final Path tempFile = Files.createFile(tempDir.resolve("myfile.txt"));

    // Write something to it.
    Files.writeString(tempFile, "Hello World");

    // Read it.
    final String s = Files.readString(tempFile);

    // Check that what was written is correct.
    assertThat("Hello World", is(s));
  }
}

Related post: JUnit: Creating Temporary Files using the TemporaryFolder @Rule