Nifty JUnit : Working with temporary files
I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.
1. DeleteOnExit
Create a temporary file with the Java File API and mark it directly as deleteOnExit()
. The created file will be deleted when the JVM exits.
package com.jdriven;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class TempFileTest {
@Test
public void testWithTempFile() throws IOException {
File tempFile = File.createTempFile("tempFile", ".txt");
tempFile.deleteOnExit();
//the tempFile will be deleted when the jvm exits
//Your test should go here
}
}
- TemporaryFolder Rule
Use the TemporaryFolder as a Rule in your JUnit Test. TemporaryFolder is an existing Rule from JUnit, see documentation here. The Rule will fire a create()
before each test method, which creates a temporary directory. After each test method a delete()
method is fired, which deletes the folder and all created files recursively.
package com.jdriven;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
public class TempFileRuleTest {
//The Folder will be created before each test method and (recursively) deleted after each test method.
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testTempFileWithRule() throws IOException {
File tempFile = temporaryFolder.newFile("tempFile.txt");
//The tempFile will be deleted when the temporaryFolder is deleted.
//Your test should go here.
}
}