【发布时间】:2012-08-29 16:56:25
【问题描述】:
我正在尝试测试一种使用 JUnit 的 TemporaryFolder 将源文件复制到目标文件的方法。但是,当我尝试运行此测试时,我得到了 Java IOException。我在哪里声明文件夹有关系吗? (我的测试类中有几个不同的测试)。如果是这样,正确的方法是什么?我问是因为我目前在此代码上方有几个单元测试,然后我尝试为文件复制设置测试。也许@Rule-@Before-@Test 块需要在自己的类中?这是我编写测试代码的 sn-p:
...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。
【问题讨论】:
标签: java unit-testing testing junit temporary-directory