如何创建带有子文件夹的 JUnit TemporaryFolder

How to create a JUnit TemporaryFolder with subfolders

我想创建一个 JUnit TemporyFolder 来代表这种树的 baseFolder:

baseFolder/subFolderA/subSubFolder
          /subFolderB/file1.txt

据我所知,我可以设置一个 TemporaryFolder 并且可以使用位于该文件夹中的 "newFolder()" 伪文件夹创建。但是我怎样才能在下面创建图层呢?特别是在测试后清理的方式。

TemporaryFolder 有一个方法 newFolder(String...folderNames) 允许您创建子目录。

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

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

temporaryFolder.newFolder(String... folderNames) 将整个层级作为参数:

@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());
}

它通过了测试并打印:

/var/folders/.../T/junit8666449860303204067/grandparent/parent/child