I/O Testing with JUnit TemporaryFolder Rule

The TemporaryFolder rule facilitates the creation and deletion of files and or folders. You can easily create a new file/folder using the TemporaryFolder#newFile() method. The file or folder is guaranteed to be deleted after the test is executed, whether it passes or fails.

In the following example we show you how easy it is to use the TemporaryFolder rule. In the @Before method we check whether the given file and folder exist. Afterwards we create the new file and folder. After the Test is run, the file and folder are automatically removed.

package com.memorynotfound.test;

import org.junit.*;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;

public class TestTemporaryFolderRule {

    @Rule
    public TemporaryFolder temp = new TemporaryFolder();

    private static final String FILE_NAME = "new-file.txt";
    private static final String FOLDER_NAME = "new-folder";

    @Before
    public void init(){
        File file = new File(temp.getRoot(), FILE_NAME);
        File folder = new File(temp.getRoot(), FOLDER_NAME);
        System.out.println("File: " + file.getName() + " exists? " + file.exists());
        System.out.println("Folder: " + folder.getName() + " exists? " + folder.exists());
    }

    @Test
    public void test_temp_folder() throws IOException {
        File file = temp.newFile(FILE_NAME);
        File folder = temp.newFolder(FOLDER_NAME);
        System.out.println("File: " + file.getName() + " exists? " + file.exists());
        System.out.println("Folder: " + folder.getName() + " exists? " + folder.exists());

    }

}

Executing the previous code multiple times will always generate the following output:

File: new-file.txt exists? false
Folder: new-folder exists? false

File: new-file.txt exists? true
Folder: new-folder exists? true

You may also like...