You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Wiremock配置请求匹配规则实现不同petId返回对应响应

问题原因分析
  • 错误1:JSONPath字段名不匹配,请求体中携带的字段是petId,你的配置中全部误写为petType,导致字段匹配逻辑本身就不成立
  • 错误2:JSON对象中存在重复键会被覆盖,你将3个matchesJsonPath规则写在同一个对象内,JSON解析时后定义的键会直接覆盖前面的,所以最终只有最后一个规则(匹配125、252)生效
  • 错误3:WireMock中同一bodyPatterns数组内的多个规则默认是与逻辑,需要显式声明才能实现满足任意规则即匹配的效果
修复后的配置

你可以直接用JsonPath的in运算符简化多值匹配逻辑,修正后的配置如下:

{
  "mappings": [
    {
      "request": {
        "method": "POST",
        "urlPath": "/mock/animal/status",
        "bodyPatterns": [
          {
            "matchesJsonPath": "$[?(@.petId in ['123','124','125'])]"
          }
        ]
      },
      "response": {
        "status": 200,
        "transformers": ["response-template"],
        "bodyFileName": "animal-success-40-200.json",
        "headers": {
          "Content-Type": "application/json"
        }
      }
    },
    {
      "request": {
        "method": "POST",
        "urlPath": "/mock/animal/status",
        "bodyPatterns": [
          {
            "matchesJsonPath": "$[?(@.petId in ['250','251','252'])]"
          }
        ]
      },
      "response": {
        "status": 200,
        "transformers": ["response-template"],
        "bodyFileName": "animal-success-80-200.json",
        "headers": {
          "Content-Type": "application/json"
        }
      }
    }
  ]
}

如果你想要用多规则声明的写法,也可以按如下格式配置,显式声明或逻辑:

"bodyPatterns": [
  {"matchesJsonPath": "$[?(@.petId == '123')]"},
  {"matchesJsonPath": "$[?(@.petId == '124')]"},
  {"matchesJsonPath": "$[?(@.petId == '125')]"},
  {"expression": "OR"}
]

内容的提问来源于stack exchange,提问作者Nekokukki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:36:06