如何向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
相关产品推荐
相关产品推荐

