首页 > 解决方案 > 如何断言json路径值大于值?

问题描述

给定从 REST 调用返回的以下 JSON:

{"Statistik Eintraege":
[{"Wert":"1","Anzahl":41},
{"Wert":"","Anzahl":482},
{"Wert":"-3","Anzahl":1},
{"Wert":"-1","Anzahl":3},
{"Wert":"-2","Anzahl":3}],
"Statistik Typ":"BlahStatistik"}

...我想验证 Wert='' 的'Anzahl' 是否大于 400(在此示例中为:482)。

我在 java 集成测试中尝试的是:

.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", greaterThan(400)));

The exception:

java.lang.ClassCastException: class net.minidev.json.JSONArray cannot be cast to class java.lang.Comparable (net.minidev.json.JSONArray is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')

    at org.hamcrest.comparator.ComparatorMatcherBuilder$1.compare(ComparatorMatcherBuilder.java:22)
    at org.hamcrest.comparator.ComparatorMatcherBuilder$ComparatorMatcher.describeMismatchSafely(ComparatorMatcherBuilder.java:86)
    at org.hamcrest.TypeSafeMatcher.describeMismatch(TypeSafeMatcher.java:82)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
    at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
    at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at 

我还能尝试什么?

标签: jsonspringtestingjsonpathhamcrest

解决方案


JsonPath 运算符[?(<expression>)]选择与给定表达式匹配的所有元素。因此,结果是一个 json 数组。

在示例[?(@.Wert == '')]中,将所有 json 节点与Wert具有空值的字段匹配。您的 json 样本只有一个与谓词匹配的项目,但通常可能有多个。要解决此问题,您必须定义一个仅匹配单个元素的更具体的表达式,或者调整匹配器以处理集合。

配套收藏:

.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", everyItem(greaterThan(400))))

推荐阅读