代码之家  ›  专栏  ›  技术社区  ›  paymer

为什么我的代码没有删除我的单元测试生成的zip文件?

  •  0
  • paymer  · 技术社区  · 10 月前

    我正在使用Spring Boot在java应用程序中工作,在我的一个UT中,我创建了一个ZIP文件(我检查了条目…),最后我试图从系统中删除它,但我尝试的方法不起作用。

    您可以在以下链接中找到我使用的代码示例: Why am I having java.io.IOException: Stream Closed in my test?

    代码简历:

    //I recover the zip 
            ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip");
            List<String> entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
    
    //Doing assertions...
    
    //Deletion of the zip
    File file = new File( "src/test/resources/exported_data_test.zip");
    file.delete();
    

    但在测试结束时,zip仍然存在于我的系统中:

    Zip not terminated

    有人能帮我删除测试结束时的zip文件吗?

    1 回复  |  直到 10 月前
        1
  •  2
  •   Mahdi Zarei    10 月前

    在对同一文件开始新操作之前,您需要将其关闭。

    根据您的示例:

    //I recover the zip 
    ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip");
    List<String> entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
    
    zipFile.close(); // Added
    
    //Doing assertions...
    
    //Deletion of the zip
    File file = new File( "src/test/resources/exported_data_test.zip");
    file.delete();
    
        2
  •  1
  •   Valerij Dobler    10 月前

    最佳实践是利用 Closable/AutoCloseable 与资源尝试接口:

    List<String> entries;
    //I recover the zip 
    try (ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip")) {
        entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
    }
    
    //Doing assertions...
    
    //Deletion of the zip
    File file = new File( "src/test/resources/exported_data_test.zip");
    file.delete();
    

    请注意,Zip是在try的括号内创建的。退出try后的作用域后,程序将在zip上调用close。