JUnit Snippets Part 1 – The Temporary Folder Rule

The TemporaryFolder Rule is the easiest way to create a temporary folder in your JUnit tests.

Available since JUnit 4.7

The following code snippet was taken from the JUnit API docs.

1
2
3
4
5
6
7
8
9
10
11
public static class HasTempFolder {
  @Rule
  public TemporaryFolder folder = new TemporaryFolder();

  @Test
  public void testUsingTempFolder() throws IOException {
      File createdFile = folder.newFile("myfile.txt");
      File createdFolder = folder.newFolder("subfolder");
      // ...
     }
 }