【问题标题】:Hamcrest matchers json subarray: is there a way to use hasItems to look for items in a subarray?Hamcrest 匹配器 json 子数组:有没有办法使用 hasItems 来查找子数组中的项目?
【发布时间】:2015-06-03 00:45:12
【问题描述】:

例如,假设我有以下 json 响应:

{
     "0": {
              "field1" : 5
              "field2" : 10
          }
     "1": {
              "field1" : 1
              "field2" : 10
          }
}

有什么方法可以验证 field1 的值是否为 5 和 1?我在这里停留在 .body 声明中:

.body("[0].field1", Matchers.hasItems(1));

我完全有可能不完全理解 hasItems 应该做什么,因为我尝试了很多 [0]、[*] 和字段名称的组合,但它们都不起作用。我还希望有一篇关于 hamcrest 和 json 的用法文章,它不仅仅涵盖最基本的情况。有谁知道我所要求的是否可能?

感谢阅读。

【问题讨论】:

    标签: json matcher hamcrest rest-assured


    【解决方案1】:

    首先,您的“json 文档”无效。它应该看起来像这样:

    {
         "0": {
                  "field1" : 5,
                  "field2" : 10
              },
         "1": {
                  "field1" : 1,
                  "field2" : 10
              }
    }
    

    由于您的目标路径仅匹配单个元素,您应该使用 equalTo(或 is)Hamcrest 匹配器:

    .body("0.field1", Matchers.equalTo(5));
    

    请注意,REST Assured 不使用“Stefan Goessner”JsonPath 语法。它使用 Groovy GPath 表达式语言。

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 2022-06-16
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2020-06-13
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多