Junit @TempDir method level scope

In this post under JUnit, I will show with example how applying “@TempDir” to a non-static field creates a temporary directory having method level scope.

When “@TempDir” is applied to a non-static field, for every test method present in the test class, JUnit will creates different temporary directory and attaches its reference to non-static field and this temporary directory exists for entire lifecycle of the particular method.

In other words, the directory is not shared by all the test methods.

A new temp directory is created at the start of every method and deleted at the end of the method.

So in a class if there are n test methods then n temp directories are created and deleted.

For our example let use the below test class.

FileOpsTest

package package22;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
public class FileOpsTest {
@TempDir
private File tempDir;
@Test
public void test1(){
System.out.println("tempDir1 name from test1: " + tempDir.getName());
}
@Test
public void test2() {
System.out.println("tempDir1 name from test2: " + tempDir.getName());
}
@Test
public void test3() {
System.out.println("tempDir1 name from test3: " + tempDir.getName());
}
}

As you can see in the above code, I declared a non-static field “tempDir” of type “File” and annotate it with “@TempDir”.

The class has 3 test methods, in each of these methods I print the temp directory name referred by “tempDir”.

Now when I run the above class, the 3 test method print the different directory name because different temp directory are created for each test method.

Below is the output for your reference.

Output

tempDir1 name from test1: junit6584468209212942004
tempDir1 name from test2: junit17074611664691647341
tempDir1 name from test3: junit4379371219533021562

In this way, we can create a temporary directory in JUnit having method level scope.

Leave a comment