Wiremock中请求JSON字段与预期不符时如何实现字段合法性校验
解决思路
方案1:使用JSON Schema严格校验(推荐)
Wiremock原生支持JSON Schema校验,通过配置additionalProperties: false可以直接禁止未定义的字段,同时可以校验字段必填、类型匹配,完美覆盖拼写错误、多余字段拦截的需求。
核心配置修改
优先级1的400拦截规则改为匹配所有不符合合法JSON结构的请求,修改后的完整配置如下:
{ "mappings":[ { "priority":1, "request":{ "method":"PATCH", "urlPath":"/pet/status", "bodyPatterns":[ { "not": { "matchesJsonSchema": { "type": "object", "properties": { "petType": {"type": "integer"}, "wildLevel": {"type": "integer"}, "petStatus": {"type": "integer"} }, "required": ["petType", "wildLevel", "petStatus"], "additionalProperties": false } } } ] }, "response":{ "status":400, "transformers":[ "response-template" ], "bodyFileName":"invalid-request.json", "headers":{ "Content-Type":"application/json" } } }, { "priority":2, "request":{ "method":"PATCH", "urlPath":"/pet/status", "bodyPatterns":[ { "matchesJsonPath":"$[?(@.petType == 404040)]" } ] }, "response":{ "status":200, "transformers":[ "response-template" ], "bodyFileName":"find-success.json", "headers":{ "Content-Type":"application/json" } } }, { "priority":3, "request":{ "method":"PATCH", "urlPath":"/pet/status" }, "response":{ "status":403, "transformers":[ "response-template" ], "bodyFileName":"data-not-found.json", "headers":{ "Content-Type":"application/json" } } } ] }
优化说明
- 能走到优先级2、3的请求已经通过了结构校验,因此不需要再重复校验字段是否存在,简化了配置
- 原优先级2的petType数值判断去掉了引号,避免数字和字符串类型不匹配导致的判断错误
方案2:低版本Wiremock兼容方案(无JSON Schema支持时使用)
如果你的Wiremock版本低于2.20.0不支持matchesJsonSchema,可以用JsonPath校验字段数量和字段存在性来实现:
优先级1的bodyPatterns改为:
"bodyPatterns": [ { "or": [ // 字段数量不等于3 { "matchesJsonPath": "$[?(@.size() != 3)]" }, // 缺少petType字段 { "matchesJsonPath": "$[?(!(@.petType))]" }, // 缺少wildLevel字段 { "matchesJsonPath": "$[?(!(@.wildLevel))]" }, // 缺少petStatus字段 { "matchesJsonPath": "$[?(!(@.petStatus))]" } ] } ]
该方案可以拦截拼写错误、多余字段、缺少字段的请求,仅严谨度略低于JSON Schema方案。
内容的提问来源于stack exchange,提问作者Nekokukki
相关产品推荐
相关产品推荐

