Junit @TempDir cleanup mode

In this post under JUnit, I will show with example how to use @TempDir different cleanup mode and what they are.

Clean up mode basically tells JUnit whether to clean up the temp directory or not, at what event to cleanup etc.

Out of the box, the following cleanup modes are available
1) ALWAYS –> always remove temp directory after the test is completed regarding was whether it is passed or failed.
2) DEFAULT –> use the default cleanup mode
3) NEVER –> never delete the temp directory
4) ON_SUCCESS –> delete the temp directory only if the test is successfully completed.

Below is the code that shows how to set it up

Test class

package package23;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.CleanupMode;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
public class FileOpsTest {
@TempDir(cleanup = CleanupMode.ON_SUCCESS)
private File tempDir;
@Test
public void testMove(){
System.out.println("tempDir1 name: " +tempDir.getName());
}
@Test
public void testDelete() {
System.out.println("tempDir1 name: " +tempDir.getName());
}
@Test
public void testCopy() {
System.out.println("tempDir1 name: " +tempDir.getName());
}
}

In the above code, at line 12 I create an instance of “File” data type named “tempDir”

At line 11, I annotated “tempDir” with “@TempDir with additional attribute (“cleanup”).

The value I have choosen in this scenario is “ON_SUCCESS”, so the “tempDir” will be deleted only if all the test passes.

If any of the tests fail, the “tempDir” will not be removed.

In this way, we can configure the clean up mode for temp directory.

Leave a comment