【问题标题】:How to assert json path value is greater than value?如何断言json路径值大于值?
【发布时间】:2021-07-16 14:37:00
【问题描述】:

鉴于以下从 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 

我还能尝试什么?

【问题讨论】:

    标签: json spring testing jsonpath hamcrest


    【解决方案1】:

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

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

    匹配集合:

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

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 2016-02-13
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多