wiremock - 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个问题:
- 如果根本没有
bar
属性,则请求不匹配 - 如果至少 1 个
bar
属性通过检查,则整个请求通过,即使其他bar
值无效(上面的示例通过)
有谁知道如何在wiremock中创建这样的规则?
解决方案
我找到了一个可能的解决方案,也许不是最简单的,但它有效。
按照你的例子:
要求:
{
"foo": [
{ "bar": "1" },
{ "qux": "oh hai" },
{ "bar": "ohnoes" }
]
}
此bodyPatterns文件用于验证每个字段是否存在,并且它具有给定的值:
"bodyPatterns" : [
{
"matchesJsonPath": "$.foo[?(@.bar == '1')]"
},
{
"matchesJsonPath": "$.foo[?(@.qux == 'oh hai')]"
},
{
"matchesJsonPath": "$.foo[?(@.bar == 'ohnoes')]"
}
]
作为参考,以下帖子对我有很大帮助:
推荐阅读
- android - 如何解决 FragmentNavigator 忽略功能的问题?
- excel - VBA用户表单从选定的文件夹位置复制pdf
- python-3.x - 为什么当我使用“ from module import *”并且我想通过帮助(模块)查看模块的功能时它不起作用?
- django - 运行 runserver 时出现“LookupError: No installed app with label 'admin'”。发生
- r - R中的时间序列标签
- google-app-engine - Google Cloud Endpoints 和 App Engine 的延迟在 1 到 2 秒之间是否正常?
- python - Google Cloud ML-Engine 在线预测错误:为已包含的占位符张量提供值
- java - FileOutputStream try-with-resources 不关闭文件描述符
- django - 使用 UniqueConstraint 解决 Django admin 中的“get() 返回多个”错误
- sas - SAS,转置表