首页 > 解决方案 > Wiremock:如何验证数组中的所有对象

问题描述

使用wiremock-standalone(版本2.29.1),我想验证一个请求,它的主体包含一个包含可选属性的对象数组。

例如,考虑这个请求:

请求正文(JSON 格式)

    { 
      "foo": [ 
        { "bar": "1" },
        { "qux": "oh hai" },
        { "bar": "ohnoes" }
      ]
    }

假设我只想在所有foo.bar属性都存在或仅包含一个数字时才匹配请求(这只是为了举例)。上面的示例不应匹配(第三个对象具有bar非数字字符的属性)。

我尝试了不同的方法,我得到的最接近的是:

{ 
  "matchesJsonPath": {
    "expression": "$.foo[*].bar",
    "or": [
      { "matches": "^\\d$" },
      { "absent": true }
    ]
  }
}

有2个问题:

有谁知道如何在wiremock中创建这样的规则?

标签: wiremockwiremock-standalone

解决方案


我找到了一个可能的解决方案,也许不是最简单的,但它有效。

按照你的例子:

要求:

{ 
  "foo": [ 
    { "bar": "1" },
    { "qux": "oh hai" },
    { "bar": "ohnoes" }
  ]
}

bodyPatterns文件用于验证每个字段是否存在,并且它具有给定的值:

"bodyPatterns" : [

      {
        "matchesJsonPath": "$.foo[?(@.bar == '1')]"
      },

      {
        "matchesJsonPath": "$.foo[?(@.qux == 'oh hai')]"
      },

      {
        "matchesJsonPath": "$.foo[?(@.bar == 'ohnoes')]"
      }
]

作为参考,以下帖子对我有很大帮助:

Wiremock 匹配JsonPath 检查忽略顺序的数组值


推荐阅读