JUnit TemporaryFolder Rule Example


TemporaryFolder rule is an extension of ExternalResource rule. It is used to create a new fresh folder with a random name under the temporary folder before the test starts running. All the files and folders created under the temporary folder will automatically be deleted once the test completes its run. By default no exception will be thrown in case the deletion fails but if we want the test to fail in case deletion fails than we need to set the flag that assures the deletion using Builder.assureDeletion(). For example:


See TestName Example to know more about test rules.

TemporaryFolder Example

In the below example we create TemporaryFolder rule. It is an instance variable annotated with @Rule. In test copySomeDataToTmpFile(), we create a new file in the temporary folder, write some data to it. Next, we assert the file size and print the file contents. We don’t have to worry about deleting the files as it will be taken care by JUnit.


package com.javarticles.junit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TemporaryFolderExample {
    public TemporaryFolder temporaryFolder = new TemporaryFolder();
    public void copySomeDataToTmpFile() throws IOException {
        File file = temporaryFolder.newFile("test");
        OutputStream out = getOutputStream(file.toPath());
        try {
            out.write("TemporaryFolder Example".getBytes());
        finally {
            try {
            catch (IOException ex) {
        assertEquals(23, Files.size(file.toPath()));        
        System.out.println("Content: " + Files.readAllLines(file.toPath()));
    private OutputStream getOutputStream(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            throw new FileNotFoundException(path + " (is a directory)");
        return Files.newOutputStream(path);


Content: [TemporaryFolder Example]

Download the source code

This was an example about JUnit TemporaryFolder rule.

You can download the source code here: junitTemporaryFolderRuleExample.zip

Comments are closed.