代码之家  ›  专栏  ›  技术社区  ›  Jeff Storey

JUnit规则临时文件夹

  •  13
  • Jeff Storey  · 技术社区  · 14 年前

    我正在创建一个 TemporaryFolder 使用 @Rule JUnit 4.7中的注释。我试图创建一个新文件夹,它是临时文件夹的子文件夹,使用 tempFolder.newFolder("someFolder") @Before (设置)我的测试方法。似乎临时文件夹在安装方法运行后被初始化,这意味着我不能在安装方法中使用临时文件夹。这种行为是否正确(且可预测)?

    2 回复  |  直到 7 年前
        1
  •  8
  •   Lennart Schedin    7 年前

    这是JUnit4.7中的一个问题。如果升级更新的JUnit(例如4.8.1),当您输入@before方法:s时,所有@rule都将运行。相关的bug报告如下: https://github.com/junit-team/junit4/issues/79

        2
  •  6
  •   Rob Spieldenner    14 年前

    这也行。 编辑 如果在@before方法中,看起来需要调用myfolder.create()。这可能是一个糟糕的实践,因为javadoc说不要调用temporaryfolder.create()。 第二次编辑 如果您不希望在@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();
        ....
      }
    }