Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JUnit TemporaryFolder with subfolders

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.

like image 913
KFleischer Avatar asked Sep 04 '16 13:09

KFleischer


1 Answers

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
like image 162
alexbt Avatar answered Oct 22 '22 02:10

alexbt