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("") returns the path string to the temporary directory used by the Java Virtual Machine. We can create any temporary resources in the, 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("", "test20140928012345"));
testDir.mkdirs(); // The given pathname might have been used in

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;


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

    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.