You need to enable JavaScript to run this app. 如何为Spring Boot控制器的CSV导出方法编写MockMvc单元测试?
优惠活动
大模型
产品
解决方案
定价
更多

如何为Spring Boot控制器的CSV导出方法编写MockMvc单元测试?

实现方案

核心思路

你只需要将本地测试文件的输入流包装为S3ObjectInputStream,再Mocks3Object.getObjectContent()返回这个流即可,后续通过MockMvc调用接口后验证响应头、响应内容和本地文件一致即可完成测试。

具体实现步骤

  • 准备测试CSV文件,放置在src/test/resources目录下,避免硬编码绝对路径
  • 读取本地测试文件的输入流,包装为S3ObjectInputStream
  • 补全Mock逻辑,关联s3Object和构造好的输入流
  • 用MockMvc发起接口请求,校验响应头、响应内容是否符合预期
完整测试代码示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.util.Objects;

@SpringBootTest
@AutoConfigureMockMvc
public class ExportControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private FileService fileService; // 替换为你实际的fileService实现类名

    @MockBean
    private S3Object s3Object;

    // 测试文件存放在src/test/resources下的文件名
    private static final String TEST_FILE_NAME = "test_leads.csv";
    private static final String PATH_TO_FILE = "test_name";
    private static final String EXPECTED_EXPORT_FILE_NAME = "leads.csv"; // 匹配你控制器里的fileName变量实际值

    @Test
    public void testReturnFile() throws Exception {
        // 1. 读取本地测试文件,构造S3ObjectInputStream
        File testFile = new File(Objects.requireNonNull(getClass().getResource("/" + TEST_FILE_NAME)).getFile());
        try (FileInputStream fileInputStream = new FileInputStream(testFile)) {
            S3ObjectInputStream s3ObjectInputStream = new S3ObjectInputStream(fileInputStream, null);

            // 2. 补全Mock逻辑
            when(fileService.getS3File(PATH_TO_FILE)).thenReturn(s3Object);
            when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream);

            // 3. 调用MockMvc发起请求,校验响应头
            MvcResult mvcResult = mockMvc.perform(post("/" + PATH_TO_FILE)
                            .contentType(MediaType.APPLICATION_OCTET_STREAM))
                    .andExpect(status().isOk())
                    .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/csv"))
                    .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + EXPECTED_EXPORT_FILE_NAME))
                    .andReturn();

            // 4. 校验响应内容和本地文件内容完全一致
            byte[] responseContent = mvcResult.getResponse().getContentAsByteArray();
            byte[] localFileContent = Files.readAllBytes(testFile.toPath());
            assertArrayEquals(localFileContent, responseContent);
        }
    }
}

注意事项

  • 示例是基于AWS SDK v1的S3ObjectAPI编写,如果你使用的是AWS SDK v2,调整S3ObjectInputStream的构造逻辑即可
  • 你原控制器代码中的fileName变量要确认取值逻辑,保证测试时EXPECTED_EXPORT_FILE_NAME和实际返回的头信息一致
  • 用try-with-resources管理文件输入流,会自动关闭资源避免泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 07:12:03