Spring应用MockMvc测试中如何比较两个JSONPath的值?
验证MockMvc响应中JSON属性的关联断言
刚好最近在写Spring接口测试时也遇到过类似的场景,要验证$.firstItem和$.location[0].path的值是否相等,有两种简单直接的方式可以实现:
方式一:直接用嵌套的jsonPath断言
这是最简洁的写法,利用Spring Test提供的jsonPath匹配器支持嵌套表达式的特性,直接让两个路径的值做对比:
mockMvc.perform(get(url)) .andExpect(status().isOk()) .andExpect(jsonPath("$.firstItem").value(jsonPath("$.location[0].path")));
这里的核心是jsonPath("$.firstItem").value(...)里可以传入另一个jsonPath表达式,框架会自动提取两个路径对应的值并判断是否相等。
方式二:自定义ResultMatcher做灵活校验
如果需要对响应内容做额外的逻辑处理(比如先判空、类型转换),可以手动提取响应体然后断言:
mockMvc.perform(get(url)) .andExpect(status().isOk()) .andExpect(result -> { // 解析响应JSON String responseBody = result.getResponse().getContentAsString(); JsonNode rootNode = new ObjectMapper().readTree(responseBody); // 提取需要对比的两个值 String firstItemValue = rootNode.get("firstItem").asText(); String firstLocationPath = rootNode.get("location").get(0).get("path").asText(); // 断言相等 Assertions.assertEquals(firstItemValue, firstLocationPath); });
小提示
- 记得确保项目依赖了
spring-boot-starter-test(或者单独的spring-test),不然jsonPath相关的匹配器会找不到。 - 如果接口返回的
location数组可能为空,建议先加一个非空断言,比如.andExpect(jsonPath("$.location[0]").exists()),避免出现空指针异常。
内容的提问来源于stack exchange,提问作者Ock
相关产品推荐
相关产品推荐

