我正在尝试测试一种使用 JUnit 的 TemporaryFolder
将源文件复制到目标文件的方法。然而,当我尝试运行此测试时,我收到了 Java IOException
。我在哪里声明文件夹有关系吗? (我的测试类中有几个不同的测试)。如果是这样,正确的方法是什么?我问这个问题是因为我目前在这段代码之上有几个单元测试,然后我尝试设置文件复制的测试。也许 @Rule
-@Before
-@Test
block 需要位于自己的类中?这是我编写测试代码的片段:
...other tests...then:
@Rule
public static TemporaryFolder tmp = new TemporaryFolder();
private File f1, f2;
@Before
public void createTestData() throws IOException {
f1 = tmp.newFile("src.txt");
f2 = tmp.newFile("dest.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1));
out.write("This should generate some \n" +
"test data that will be used in \n" +
"the following method.");
out.close();
}
@Test
public void copyFileTest() {
out.println("file 1 length: " + f1.length());
try {
copyFile(f1, f2);
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
if (f1.length() != f2.length())
fail();
else if (!f1.equals(f2))
fail();
assertSame(f1, f2);
}
当我运行这个测试类时,我的所有 11 个测试现在都失败了(之前通过了),并且我收到 java.io.IOException: No such file or directory
。
最佳答案
所以看看 JUnit Javadoc ,我发现 @Rule
下的任何声明都必须是公共(public)的,并且不是静态的。所以我拿出了静态文件,然后就得到了:
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
我仍然不确定当您的类中有其他不使用 @Rule 声明的单元测试时,在何处进行此声明是否重要,但这确实允许我运行成功通过我的测试。
关于java - JUnit : When do I declare a TemporaryFolder object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12182916/