我有一個測試,我希望我在Junit測試中創建的文件在測試完成後被刪除,我使用junit.rules.TemporaryFolder來執行此操作。Junit測試後不會刪除臨時文件
這是我的測試怎麼一回事:
public class FileUtilityIntegrationTest {
static TemporaryFolder _tempFolder2;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void testCreateZip() throws IOException {
File zipFile = testFolder.newFile("fileName.zip");
File tempDir = testFolder.newFolder("tempDir");
File innerFile = new File(tempDir, "testFile.txt");
try (FileOutputStream fos = new FileOutputStream(innerFile)) {
fos.write("this is in testFile".getBytes());
}
FileUtility.createZip(tempDir, zipFile);
assertTrue(TestUtil.zipFileContainsAndNotEmpty(zipFile, innerFile.getName()));
}
@After
public void after() {
_tempFolder2 = testFolder;
System.out.println(_tempFolder2.getRoot().exists()); //true
}
@AfterClass
public static void afterClass() {
System.out.println(_tempFolder2.getRoot().exists()); //true
}
}
正如你所看到的文件/文件夾沒有在測試完成後刪除。我也想明確地關閉fos
沒有工作,要麼
下面是實際的方法,我想測試:
public static void createZip(File inputDirectory, File zipFile) throws IOException {
classLogger.debug("Creating Zip '" + zipFile.getPath() + "'");
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)){
// create zip file from files in directory
for (File file : inputDirectory.listFiles()) {
if (file.isFile()) {
classLogger.debug("File to be zipped: " + file.getAbsolutePath());
addToZipFile(file, zos);
}
}
zos.finish();
} catch (IOException e) {
classLogger.error("Error processing zip file: " + zipFile.getPath(), e);
throw e;
}
}
API文檔說'的TemporaryFolder規則允許文件和文件夾的創建應該被刪除,請檢查temDir位置當測試方法結束時(無論是否通過)。此規則不檢查刪除是否成功。如果刪除失敗,將不會拋出異常。也許你嘗試手動調用'@ After'方法中的'tempFolder.delete()'? –
是手動刪除它們是我計劃要做的事情,如果我無法找出爲什麼Junit不會自動刪除它們, – Snedden27