Core Java

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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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));
  }
}

Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Creating Temporary Files with JUnit 5

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button