2017-05-25 97 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