我正在使用JUnit 4.7中的TemporaryFolder
注释创建@Rule
。我尝试在我的测试的tempFolder.newFolder("someFolder")
(设置)方法中使用@Before
创建一个新文件夹,该文件夹是临时文件夹的子文件夹。似乎临时文件夹在安装方法运行后被初始化,这意味着我无法在setup方法中使用临时文件夹。这是正确的(可预测的)行为吗?
答案 0 :(得分:8)
这是Junit 4.7中的一个问题。如果你升级一个较新的Junit(例如4.8.1),当你输入@Before方法时,所有@Rule都会被运行:s。相关的错误报告是:https://github.com/junit-team/junit4/issues/79
答案 1 :(得分:6)
这也有效。 编辑如果在@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();
....
}
}