2010-04-27 77 views
13

我使用JUnit 4.7中的@Rule注释创建了TemporaryFolder。我尝试使用我测试的@Before(设置)方法中的tempFolder.newFolder("someFolder")创建一个新文件夹,该文件夹是临时文件夹的子项。看起来临时文件夹在setup方法运行后被初始化,这意味着我不能在setup方法中使用临时文件夹。这是正确的(和可预测的)行为?JUnit Rule TemporaryFolder

回答

8

这是Junit 4.7中的问题。如果您升级较新的Junit(例如4.8.1),则在输入@Before方法时将运行所有的@Rule:s。一个相关的错误报告是这样的:https://github.com/junit-team/junit4/issues/79

+0

谢谢。生病不得不升级。 – 2010-05-05 23:16:38

+2

即使使用JUnit 4.8.2,在Windows 7上TemporaryFolder规则无法正常工作,我也不会这么做。 看起来像是一个权限问题。 – exception 2012-03-27 13:26:25

+1

链接被破坏;工作之一:https://github.com/junit-team/junit4/issues/79 – jwd 2017-05-04 22:03:30

6

这也适用。 编辑如果在@Before方法中它看起来像myfolder.create()需要调用。这可能是不好的做法,因为javadoc说不要调用TemporaryFolder.create()。 2nd编辑看起来像你必须调用该方法来创建临时目录,如果你不想让它们在@Test方法中。另外请确保关闭您在临时目录中打开的任何文件,否则它们将不会自动删除。

<imports excluded> 

public class MyTest { 

    @Rule 
    public TemporaryFolder myfolder = new TemporaryFolder(); 

    private File otherFolder; 
    private File normalFolder; 
    private File file; 

    public void createDirs() throws Exception { 
    File tempFolder = myfolder.newFolder("folder"); 
    File normalFolder = new File(tempFolder, "normal"); 
    normalFolder.mkdir(); 
    File file = new File(normalFolder, "file.txt"); 

    PrintWriter out = new PrintWriter(file); 
    out.println("hello world"); 
    out.flush(); 
    out.close(); 
    } 

    @Test 
    public void testSomething() { 
    createDirs(); 
    .... 
    } 
} 
+0

虽然这确实会创建一个新文件夹,但tempFolder实际上并不在临时位置(它位于工作目录中),因为myFolder尚未设置为临时位置。它也不会被清理干净。 – 2010-04-27 17:55:26

+0

这会将目录保留在$ TEMP或%TEMP%目录中,因此仍在寻找真正的答案。 – 2010-04-27 18:53:45