2017-05-25 86 views
1

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

API文档说'的TemporaryFolder规则允许文件和文件夹的创建应该被删除,请检查temDir位置当测试方法结束时(无论是否通过)。此规则不检查删除是否成功。如果删除失败,将不会抛出异常。也许你尝试手动调用'@ After'方法中的'tempFolder.delete()'? –

+0

是手动删除它们是我计划要做的事情,如果我无法找出为什么Junit不会自动删除它们, – Snedden27

回答

0

测试RULLE调用applyAll方法,该方法后,您的JUnit后调用。 它呼吁finally块。所以,如果物理删除或not.Check 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; 
    } 
+0

我检查物理文件夹/文件,它没有删除那里 – Snedden27

+0

可以转到Temporaryfolder类和调试点在删除方法中看到它为什么不工作。 –

+0

是的,这是一个好主意,但我认为我确实发现了它,似乎我正在打开一个流,这是造成这个 – Snedden27