我有一个测试,我希望我在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