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

Spring Boot WebTestClient模拟上传MockMultipartFile运行报错求助

问题原因

你当前使用的MockMultipartFile是Servlet API栈的测试工具类,而WebTestClient默认适配响应式技术栈,序列化请求时Jackson无法处理MockMultipartFile内部持有的ByteArrayInputStream输入流对象,因此抛出序列化失败异常。

解决方案

推荐使用MultipartBodyBuilder构造Multipart请求体,无需依赖Servlet栈的MockMultipartFile,示例代码如下:

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;

// 读取测试文件资源
Resource testFile = new ClassPathResource("/Test.txt");

// 构造Multipart请求内容
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("files", testFile)
        .filename("Test.txt") // 指定上传文件名
        .contentType(MediaType.TEXT_PLAIN); // 指定文件MIME类型

webTestClient.post()
        .uri("/foo")
        .header("test", "1")
        .header("test1", "1")
        .contentType(MediaType.MULTIPART_FORM_DATA)
        .bodyValue(builder.build())
        .exchange()
        .expectStatus().isOk();

如果你的测试场景需要直接传入字节数组,也可以替换part的入参:

// 把文件读为字节数组,测试类可直接声明抛出IOException即可
byte[] fileContent = this.getClass().getResourceAsStream("/Test.txt").readAllBytes();
builder.part("files", fileContent)
        .filename("Test.txt")
        .contentType(MediaType.TEXT_PLAIN);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 22:45:05