Search code examples
javaunit-testingzip

Why my code is not deleting the zip file generated by my unit test?


I'm working in a java application with Spring Boot, and in one of my UT I create a ZIP file (I check the entries...) and at the end I'm trying to delete it from my system, but what I'm trying is not working.

You can find an example of the code I'm using in the following link: Why am I having java.io.IOException: Stream Closed in my test?

Resume of the code:

//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();

But at the end of the test the zip still exists on my system:

Zip not terminated

Can someone help me delete the zip file at the end of the test?


Solution

  • Before starting new operation on the same file, you need to close it.

    Based on your example:

    //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();