我想測試一個方法,使用JUnit的TemporaryFolder
將源文件複製到dest文件。但是,當我嘗試運行此測試時,我得到一個Java IOException
。我在哪裏做文件夾的聲明有關係嗎? (我的測試課有幾個不同的測試)。如果是這樣,那麼做到這一點的正確方法是什麼?我問,因爲我目前有幾個單元測試高於此代碼,然後我嘗試設置文件複製的測試。也許@Rule
-@Before
-@Test
塊需要在它自己的類中?這裏是我已經編寫測試代碼片段:JUnit:我什麼時候聲明一個TemporaryFolder對象?
...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
。