如何在WireMock中使用逻辑‘OR’组合多个bodyPattern?
在WireMock中用OR逻辑组合bodyPattern
WireMock支持通过or逻辑操作符组合多个bodyPattern,无需为每个参数单独配置Stub。
先纠正你原配置的问题
你原来的写法里,同一个JSON对象中重复定义了matchesJsonPath键,这在JSON语法中是无效的——后面的键会覆盖前面的,所以实际生效的只有[?(!(@.appointment.id))]这一条规则,并非同时匹配两个缺失条件。
实现OR逻辑的正确配置
通过在bodyPatterns中使用or包裹多个匹配规则,就能实现任一规则满足即匹配的效果:
{ "request": { "urlPath": "/somePath", "method": "POST", "bodyPatterns": [ { "or": [ { "matchesJsonPath": "[?(!(@.product.group))]" }, { "matchesJsonPath": "[?(!(@.appointment.id))]" } ] } ] }, "response": { "status": 400, "jsonBody": [ { "code":400, "detail":"Missing Required Parameter", "field":"product.group, appointment.id", "message":"The request is missing a required parameter." } ], "headers": { "Content-Type": "application/json" } } }
配置说明
bodyPatterns数组中的元素默认是AND关系,这里我们在单个元素内用or数组包裹两个匹配规则,让这两个规则变成OR关系。- 只要请求JSON中缺失
product.group,或者缺失appointment.id,就会触发这个400错误响应。 - 如果需要更复杂的嵌套逻辑(比如AND与OR组合),WireMock也支持多层嵌套的逻辑操作符。
内容的提问来源于stack exchange,提问作者Biswajit
相关产品推荐
相关产品推荐

