Junit测试后不会删除临时文件

时间:2017-05-25 16:00:06

标签: 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;
    }
}

1 个答案:

答案 0 :(得分:0)

测试rulle调用applyAll方法,在你的junit之后调用方法。 它是最后一个块的调用。所以请检查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;
    }