如何使用子文件夹创建JUnit TemporaryFolder

时间:2016-09-04 13:00:25

标签: java junit junit4 junit-rule

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

baseFolder/subFolderA/subSubFolder
          /subFolderB/file1.txt

据我了解,我可以设置一个TemporaryFolder,而不是用" newFolder()"位于该文件夹中的伪文件夹。但是如何在下面创建图层?特别是在测试后清理的方式。

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

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

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

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