如何使用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
相关产品推荐
相关产品推荐

