Why am I having java.io.IOException: Stream Closed in my test?

  Kiến thức lập trình

While working on the UT of a java 11 with Springboot project I have found the following stacktrace:

java.io.IOException: Stream Closed
    at java.base/java.io.FileInputStream.readBytes(Native Method)
    at java.base/java.io.FileInputStream.read(FileInputStream.java:279)
    at com.amazonaws.internal.SdkFilterInputStream.read(SdkFilterInputStream.java:90)
    at java.base/java.io.FilterInputStream.read(FilterInputStream.java:107)
    at com.comsurf.services.export.ExportServiceImpl.lambda$exportDocumentsFicheToZip$26(ExportServiceImplementation.java:795)

The line giving problems is the while line of the following code:

//the map is fullfilled with the name of the objects/documents and the content of the documents recovered from s3 (Map<String, S3ObjectInputStream> s3ObjectInputStream)

Map<String, S3ObjectInputStream> s3ObjectInputStreamMap...


s3ObjectInputStreamMap.keySet().forEach(key -> {
                var zipEntry = new ZipEntry(key);
                try {
                    zipOutputStream.putNextEntry(zipEntry);
                    var objectContent = s3ObjectInputStreamList.get(key);
                    var bytes = new byte[1024];
                    int length;
                    while ((length = objectContent.read(bytes)) >= 0) {
                        zipOutputStream.write(bytes, 0, length);
                    }
                    objectContent.close();
                    zipEntry.clone();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

The case is that the code when used in the application it works well, but in the test it does the first iteration of the while and in the second iteration the error shown in the stack trace pops.

I have created the following method to create the objects to return from S3Service(mocked service) in the test:

private static S3Object getS3Object(String fileName) throws FileNotFoundException {
        S3Object s3Object = new S3Object();
        s3Object.setKey(fileName);
        File initialFile = new File(FILE_ADRESS+ "/" + fileName);
        InputStream targetStream = new FileInputStream(initialFile);
        s3Object.setObjectContent(targetStream);
        return s3Object;
    }

I don’t know why I’m having the error java.io.IOException: Stream Closed. If someone could please give an explanation/solution to this problem?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT