java - Junit测试后临时文件没有被删除

标签 java file-io junit

我有一个测试,我希望在测试完成后删除我在 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/

相关文章:

java - 将类型参数传递给接口(interface)方法

java - 如何在 XPath 查询中使用 Java String 变量

java - 根据节点中存储的数据突出显示 jtree 中的特定节点

java - 代码工作正常,因为 web 服务在 junit 中出现错误

jenkins - ANT 任务 maxmemory 和通过 jvmarg 设置堆大小之间的区别?

junit - 如何在 Android Studio 中将测试方法或类作为 Android 测试运行

java - 读取整个 XML 行并将其保存到数组中? JDOM

java - 我应该在哪里放置 close() 方法?

python - Scrapy IO错误: [Errno 22] invalid mode ('wb' ) or filename

c++ - 不明白 sscanf() 函数是如何工作的