Sunday, September 28, 2014

Temporary Folders in JUnit Test Cases

On writing test cases, we sometimes need a temporary directory to store test resources.

In Java, System.getProperty("java.io.tmpdir") returns the path string to the temporary directory used by the Java Virtual Machine. We can create any temporary resources in the java.io.tmpdir, but we need to check if the name of each resource to be created has been used and clean it up after testing.

File testDir = new File(System.getProperty("java.io.tmpdir", "test20140928012345"));
testDir.mkdirs(); // The given pathname might have been used in java.io.tmpdir.
...
testDir.delete();

JUnit provides a class TemporaryFolder with the @Rule annotation (as of the version 4.7), which helps us manage temporary resources much easier.

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

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class FileUtilsTest {
    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    public void testWrtieStringToFile() throws IOException {
        final File dir = tempFolder.newFolder("subfolder");
        final String expected = "deadbeef";
        final File outfile = new File(dir, "a.txt");
        FileUtils.writeStringToFile(outfile, expected);
        assertEquals(expected, FileUtils.readFileToString(outfile));
    }
    ...
}

After invoking each @Test block, the JUnit runner cleans up all the resources under the temporary directory created by an instance of TemporaryFolder.