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

如何向MockMvc传递CartDto对象作为参数进行接口测试?

如何在MockMvc测试中传递CartDto作为请求体参数?

你要测试的接口通过@RequestBody接收CartDto对象,且指定了消费application/json格式的请求,要在MockMvc测试中传递这个对象,需要将CartDto序列化为JSON字符串并设置正确的请求头,具体实现如下:

完整测试代码示例

// 1. 构造测试用的CartDto实例,填充测试数据
CartDto testCartDto = new CartDto();
testCartDto.setProductId(1L);
testCartDto.setQuantity(3);
// 根据你的CartDto结构补充其他属性

// 2. 将对象序列化为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String requestJson = objectMapper.writeValueAsString(testCartDto);

// 3. 构建MockMvc请求,设置内容类型和请求体
MvcResult mvcResult = mockMvc.perform(post("/user/addItemIntoCart")
                .contentType(MediaType.APPLICATION_JSON)
                .content(requestJson)
        )
        .andExpect(status().isOk())
        .andReturn();

关键说明

  • 必须指定contentType(MediaType.APPLICATION_JSON),匹配接口的consumes配置,否则Spring无法正确解析请求体
  • 确保CartDto类有完整的getter/setter方法(或使用Lombok的@Data注解),否则Jackson无法正常完成对象与JSON的序列化转换
  • 如果是Spring Boot测试环境,可以直接@Autowired注入ObjectMapper,无需手动实例化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:01:36