You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java测试中出现java.io.IOException: Stream Closed的排查与解决

问题原因分析

测试时出现java.io.IOException: Stream Closed的核心原因是Mockito返回了同一个S3Object实例:

  • 你的测试代码中when(s3Service.getObject(Mockito.anyString())).thenReturn(getS3Object("image.jpg"))只会执行一次getS3Object,生成一个包含FileInputStream的S3Object实例;
  • 第一次循环读取并关闭了这个流后,第二次循环调用getObject仍会拿到同一个已关闭的流,导致读取时抛出流关闭异常;
  • 生产环境正常是因为每次调用S3的getObject都会返回全新的输入流,不会出现重复使用已关闭流的情况。
解决方案

1. 修改Mockito返回逻辑,保证每次调用生成新实例

将thenReturn替换为thenAnswer,确保每次调用getObject都会生成新的S3Object和对应的输入流:

when(s3Service.getObject(Mockito.anyString())).thenAnswer(invocation -> {
    // 这里可以根据传入的fileName参数返回对应文件,保持原逻辑则直接返回getS3Object("image.jpg")
    return getS3Object("image.jpg");
});

2. 修复业务方法中的资源管理问题

原minimalExample方法存在多处资源管理隐患,修改后避免流重复关闭、异常吞掉等问题:

public ZipOutputStream minimalExample(ZipOutputStream zipOutputStream, String directoryName) {
    try {
        List<String> listDocumentType = List.of("doc1", "doc2", "doc3", "doc4");
        for (String docType : listDocumentType) {
            String fileName = directoryName + '/' + docType + "_export.jpg";
            S3Object s3Object = s3Service.getObject(fileName);
            if (s3Object != null) {
                String entryName = docType + "_export.jpg";
                ZipEntry zipEntry = new ZipEntry(entryName);
                zipOutputStream.putNextEntry(zipEntry);
                
                // 用try-with-resources自动关闭S3输入流,避免资源泄漏
                try (S3ObjectInputStream objectContent = s3Object.getObjectContent()) {
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = objectContent.read(bytes)) >= 0) {
                        zipOutputStream.write(bytes, 0, length);
                    }
                }
                zipOutputStream.closeEntry();
            }
        }
        // 不要在这里关闭zipOutputStream,交给外部try-with-resources自动处理
    } catch (IOException e) {
        logger.log(Level.LOW, "压缩文件失败", e); // 打印完整异常栈便于排查
        throw new RuntimeException("压缩文件处理失败", e); // 抛出异常让上层感知,不要静默吞掉
    }
    return zipOutputStream;
}

3. 修正测试代码中的ZipFile使用错误

原代码直接用File强转ZipFile是错误的,改用try-with-resources管理ZipFile资源:

File zipFile = new File("src/test/resources/exported_data_test.zip");
try (ZipFile zf = new ZipFile(zipFile)) {
    List<String> entries = zf.stream().map(ZipEntry::getName).collect(Collectors.toList());
    
    // 断言逻辑
    assertNotNull(entries);
    assertTrue(entries.stream().filter(ent -> ent.contains(".jpg")).count() == 4);
    List<String> imagesNameList = List.of("doc1_export.jpg", "doc2_export.jpg", "doc3_export.jpg", "doc4_export.jpg");
    entries.forEach(imageName -> assertTrue(imagesNameList.contains(imageName)));
}

内容的提问来源于stack exchange,提问作者paymer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:42:12