我有一个测试,我希望在测试完成后删除我在 Junit 测试中创建的文件,我使用 junit.rules.TemporaryFolder 来执行此操作。
这就是我的测试过程:
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;
}
}
最佳答案
测试规则调用 applyAll 方法,该方法在 junit after 方法之后调用。
它是在finally block 上调用的。因此,请检查temDir位置是否物理删除。检查File tempDir
字段以获取临时位置
before();
try {
base.evaluate();
} finally {
after();
}
private static Statement applyAll(Statement result, Iterable<TestRule> rules,
Description description) {
for (TestRule each : rules) {
result = each.apply(result, description);
}
return result;
}
关于java - Junit测试后临时文件没有被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44184894/