JUnit 规则临时文件夹

2022-09-04 21:17:32

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


答案 1

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


答案 2

这也有效。EDIT 如果在@Before方法中看起来像 myfolder.create() 需要调用。这可能是不好的做法,因为javadoc说不要调用TemporalFolder.create()。第 2 次编辑看起来,如果您不希望在@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();
    ....
  }
}

推荐