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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:24:43