In this post under JUnit, I will show with example how applying “@TempDir” to a static field creates a temporary directory having class level scope.
When “@TempDir” is applied to a static field, JUnit creates temporary directory and attaches its reference to static field and it exists for the entire test class lifecycle.
In other words, the directory is shared by all the test methods and is typically cleaned up after the test class execution finishes.
For our example let use the below test class.
FileOpsTest
package package21;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import java.io.File;public class FileOpsTest { @TempDir private static File tempDir1; @Test public void test1(){ System.out.println("tempDir1 name from test1: " +tempDir1.getName()); } @Test public void test2() { System.out.println("tempDir1 name from test2: " +tempDir1.getName()); } @Test public void test3() { System.out.println("tempDir1 name from test3: " +tempDir1.getName()); }}
As you can see in the above code, I declared a static field “tempDir1” of type “File” and annotate it with “@TempDir”.
This will create a temporary directory and attaches its reference to “tempDir1”.
The class has 3 test methods, in each of these methods I print the temp directory name referred by “tempDir1”.
Now when I run the above class, the 3 test method print the same directory name because the temp directory is shared across all the test method.
Below is the output for your reference.
Output
tempDir1 name from test1: junit8075164703018358878tempDir1 name from test2: junit8075164703018358878tempDir1 name from test3: junit8075164703018358878
In this way, we can create a temporary directory in JUnit having class level scope.