15

I would like to create a JUnit TemporyFolder that represents the baseFolder of such a tree:

baseFolder/subFolderA/subSubFolder
          /subFolderB/file1.txt

As far as I understand I can setUp a TemporaryFolder and than can create with "newFolder()" pseudo Folders that are located in that very folder. But How can I create layers underneath? Especially in a way that is cleaned up after the test.

KFleischer
  • 942
  • 2
  • 11
  • 33

2 Answers2

16

temporaryFolder.newFolder(String... folderNames) takes the whole hierarchy as parameters:

@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

@Test
public void test() throws Exception {
    File child = temporaryFolder.newFolder("grandparent", "parent", "child"); //...

    assertEquals("child", child.getName());
    assertEquals("parent", child.getParentFile().getName());
    assertEquals("grandparent", child.getParentFile().getParentFile().getName());
    System.out.println(child.getAbsolutePath());
}

It passes the tests and prints:

/var/folders/.../T/junit8666449860303204067/grandparent/parent/child
alexbt
  • 16,415
  • 6
  • 78
  • 87
  • 3
    What about the file inside the subfolder "file1.txt"? How to create it? – Manjunath M Dec 30 '19 at 06:56
  • 1
    Do TemporaryFolder instances get automatically deleted? This says they "should be deleted": https://junit.org/junit4/javadoc/latest/org/junit/rules/TemporaryFolder.html. This says they're "guaranteed to be deleted": https://junit.org/junit4/javadoc/4.9/org/junit/rules/TemporaryFolder.html. – Woodchuck Aug 15 '20 at 20:40
  • @JWoodchuck I think the idea is that there are exceptional cases where the folder will not be deleted successfully: https://stackoverflow.com/questions/16494459/why-isnt-junit-temporaryfolder-deleted#comment54739758_16494459 – alexbt Aug 16 '20 at 13:22
0

TemporaryFolder has a method newFolder(String...folderNames) that allows you to create subdirectories.

tempFolder.newFolder("subFolderA", "subSubFolder")

http://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html#newFolder(java.lang.String...)

Jimmy T.
  • 4,033
  • 2
  • 22
  • 38