如何单元测试接收包含multipart文件的Java对象的REST端点
解决方案
你要测试的@ModelAttribute接口接收的是multipart/form-data类型请求,直接使用Spring自带的MockMvc构造对应请求即可,Spring会自动将普通参数、文件列表绑定为完整的Person对象,无需手动组装实体。
测试代码实现
依赖说明
常规Spring Boot项目的spring-boot-starter-test依赖已经内置MockMvc相关组件,无需额外引入依赖。
完整测试类代码
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(PersonRestController.class) public class PersonRestControllerTest { @Autowired private MockMvc mockMvc; @MockBean private IPersonService personService; @Test public void testSavePersonSuccess() throws Exception { // 构造测试文件列表 MockMultipartFile image1 = new MockMultipartFile( "images", "cover.jpg", "image/jpeg", "测试图片1内容".getBytes() ); MockMultipartFile image2 = new MockMultipartFile( "images", "detail.png", "image/png", "测试图片2内容".getBytes() ); // 模拟Service层返回 when(personService.savePerson(any(Person.class))).thenReturn("张三"); // 构造请求并执行测试 mockMvc.perform(multipart("/v1/save") .param("name", "张三") .param("age", "25") .file(image1) .file(image2) ) .andExpect(status().isCreated()) .andExpect(content().string("张三")); } }
关键说明
- 构造请求时使用
multipart()方法,对应multipart/form-data请求类型,和@ModelAttribute的参数绑定规则匹配 - 普通字段通过
param()传入,参数名必须和Person类的属性名完全一致 - 文件构造方法的第一个入参必须和Person类中
images属性名完全一致,多个文件使用相同参数名即可自动绑定为List - Spring会自动完成所有参数到Person对象的绑定,不需要手动实例化Person对象传入,符合你测试整个实体的需求
- 注意你原控制器代码中
@RequestMapping("/v1")缺少闭合引号,需要修正为@RequestMapping("/v1")避免启动报错
内容的提问来源于stack exchange,提问作者Shubham Wankhede
相关产品推荐
相关产品推荐

