Managing file and directory operations is a frequent need in automated testing. When testing code that involves creating, modifying, or deleting files, it is important to ensure that the test environment is clean. In JUnit 5, this process has been simplified with built-in support for temporary directories. This built-in support helps in automatically cleaning up temporary records after the tests are run and maintained.
Prerequisites:
- Basic knowledge of the Java and JUnit Framework.
- Maven for building dependency management.
- JDK and IntelliJ IDEA are installed in your system.
Maven Dependency
Add the below-mentioned dependency to the pom.xml file to use JUnit 5 with Maven.
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Temporary Directory
A temporary directory is a short-lived directory used specifically during test execution. Once the test finishes, JUnit 5 ensures that the directory is automatically deleted, keeping the test environment clean. With the @TempDir annotation, JUnit 5 provides a simple way to create and manage these temporary directories, allowing you to handle files and directories required only for the duration of the test.
Using @TempDir in JUnit 5
The @TempDir annotation in JUnit 5 can be used to create a temporary directory. It can be applied as a method parameter or as a field within the test class.
Example 1: Using @TempDir as a Method Parameter
In this approach, @TempDir is used as a parameter of the test method, and JUnit automatically creates the temporary directory before the test runs:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TemporaryDirectoryTest {
@Test
void testCreateFileInTempDirectory(@TempDir Path tempDir) throws IOException {
Path tempFile = tempDir.resolve("sampleFile.txt");
Files.createFile(tempFile);
// Assert that the file exists
assertTrue(Files.exists(tempFile));
}
}
In this example,
- This test method creates a temporary directory and then creates a file named
sampleFile.txtinside it. - The assertion checks whether the file was successfully created.
Example 2: Using @TempDir as a Field:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TemporaryDirectoryTest {
@TempDir
Path tempDir; // Temporary directory created before each test
@Test
void testCreateFileInTempDirectory() throws IOException {
Path tempFile = tempDir.resolve("exampleFile.txt");
Files.createFile(tempFile);
// Assert that the file exists
assertTrue(Files.exists(tempFile));
}
}
In this example,
- The test method creates a file named
exampleFile.txtinside thetempDir. - The assertion checks if the file exists in the temporary directory.
Project Implementation to Use @TempDir in JUnit 5
This example project focuses on testing file operations using the @TempDir feature. Below are the steps to create a Maven-based project structure, Java classes, and test cases that utilize temporary directories.
Step 1: Create a New Maven Project
Create a new Maven project using IntelliJ IDEA with the following options:
- Name:
tempdir-junit5-example - Build System: Maven
Click on the Create button.

Project Structure
After the project creation done, set the file structure would be as shown in the below image:

Step 2: Maven pom.xml
Add the below dependencies in the pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>tempdir-junit5-example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JUnit 5 Dependency -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Maven Surefire Plugin for running tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</build>
</project>
Step 3: FileService.java
Create the FileService class and this class. This class contains methods to handle file creation and writing content to the files.
package com.gfg;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileService {
// Create a file with the specified name in the given directory and write content to it.
public Path createFileWithContent(Path directory, String fileName, String content) throws IOException {
// create the file path
Path filePath = directory.resolve(fileName);
// Write content to the file
Files.writeString(filePath, content);
return filePath; // Return the created file path
}
// Check if a file exists at the specified path.
public boolean isFileExist(Path filePath) {
// Check if the file exists
return Files.exists(filePath);
}
}
Step 4: MainApplication.java
Create the MainApplication class and this class demonstrate file creation using the FileService.
package com.gfg;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MainApplication {
public static void main(String[] args) {
FileService fileService = new FileService();
try {
Path currentDir = Paths.get(System.getProperty("user.dir"));
String fileName = "demoFile.txt";
String content = "This is a demo file created using the FileService.";
Path filePath = fileService.createFileWithContent(currentDir, fileName, content);
System.out.println("File created at: " + filePath.toString());
if (fileService.isFileExist(filePath)) {
System.out.println("File exists: " + filePath);
String fileContent = Files.readString(filePath);
System.out.println("File content: " + fileContent);
} else {
System.out.println("File creation failed.");
}
} catch (IOException e) {
System.err.println("An error occurred while creating or reading the file: " + e.getMessage());
}
}
}
Step 5: FileServiceTest.java
Create the FileServiceTest class, which contains JUnit 5 test methods that use the @TempDir to create temporary directories and files for testing purposes.
import com.gfg.FileService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FileServiceTest {
@TempDir
Path tempDir; // Temporary directory created for testing
@Test
void testCreateFileWithContent() throws IOException {
FileService fileService = new FileService();
// Define the file name and content
String fileName = "testFile.txt";
String content = "This is a test file.";
Path filePath = fileService.createFileWithContent(tempDir, fileName, content);
assertTrue(fileService.isFileExist(filePath));
}
}
Step 6: Run the Application
After completing the project, we will run the application and it will display the below output in console.

Step 7: Running the Tests
Now, run the tests using the below maven command:
mvn testOutput:

This results indicates that both the test methods have passed successfully, and the temporary directories and files are managed correctly during the test execution.