JUnit 5测试REST API GET全量查询接口断言失败如何解决
MockMvc 测试返回JSON与实体类对象断言失败的解决方法
- 核心思路是将MockMvc返回的JSON响应字符串反序列化为对应实体类对象列表,再和预期结果做断言,Spring Boot环境下可直接用内置的Jackson工具完成转换:
- 测试类注入
ObjectMapper,无需额外配置,Spring Boot会自动完成实例化
@SpringBootTest @AutoConfigureMockMvc public class ExampleControllerIntTest { @Autowired private MockMvc mockMvc; // 注入Jackson序列化工具 @Autowired private ObjectMapper objectMapper; // 你的预期测试数据 private List<MExample> expectedList; @BeforeEach void init() { // 初始化你的预期测试数据逻辑 expectedList = List.of(new MExample(1, "测试1"), new MExample(2, "测试2")); } }
- 执行MockMvc请求后,将响应体JSON转换为
List<MExample>对象再做断言,注意集合带泛型的场景需要用TypeReference规避类型擦除问题
@Test void shouldReturnAllExamples() throws Exception { // 执行GET请求 MvcResult mvcResult = mockMvc.perform(get("/api/examples") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); // 读取响应JSON字符串 String responseJson = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); // 反序列化为MExample对象列表 List<MExample> actualList = objectMapper.readValue(responseJson, new TypeReference<List<MExample>>() {}); // 断言实际结果与预期结果一致 org.junit.jupiter.api.Assertions.assertEquals(expectedList, actualList); }
- 注意事项:
- 确保
MExample类有无参构造方法,且所有参与序列化的属性都有对应的getter、setter方法,否则Jackson反序列化会抛出异常 - 如果你只需要校验部分关键字段,不需要全量对比对象,也可以直接用MockMvc内置的jsonPath语法做断言,省去转对象的步骤:
- 确保
@Test void shouldReturnAllExamplesByJsonPath() throws Exception { mockMvc.perform(get("/api/examples") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) // 校验返回列表长度为2 .andExpect(jsonPath("$", org.hamcrest.Matchers.hasSize(2))) // 校验第一个元素的id为1,name为测试1 .andExpect(jsonPath("$[0].id", org.hamcrest.Matchers.is(1))) .andExpect(jsonPath("$[0].name", org.hamcrest.Matchers.is("测试1"))); }
内容的提问来源于stack exchange,提问作者summerisbetterthanwinter
相关产品推荐
相关产品推荐

