如何用WireMock验证请求中不包含指定参数(JSON配置)
正确的WireMock JSON配置方案
核心思路
针对x-www-form-urlencoded格式的请求,需同时满足两个条件:
grant_type参数值为authorization_codecode参数完全不存在(并非参数值为空)
WireMock提供了专门的表单参数匹配规则,直接通过formParameter和formParameterMissing组合即可实现需求,无需复杂正则匹配。
完整配置代码
{ "request": { "method": "POST", "url": "/token", "headers": { "Content-Type": { "equalTo": "application/x-www-form-urlencoded" } }, "formParameters": { "grant_type": { "equalTo": "authorization_code" } }, "formParameterMissing": "code" }, "response": { "status": 400, "headers": { "Content-Type": "application/json" }, "body": "{\"error\": \"invalid_request\", \"error_description\": \"The code parameter is required when grant_type is authorization_code\"}" } }
配置说明
headers指定Content-Type为application/x-www-form-urlencoded,确保只匹配目标格式的请求formParameters精准匹配grant_type=authorization_code的参数条件formParameterMissing: "code"直接判定请求中不存在code参数,避免了正则匹配的边界问题- 响应部分可根据实际需求修改错误状态码和返回格式,示例采用OAuth2标准错误响应格式
之前尝试失败的原因
- 使用
contains/notContain匹配body:表单参数顺序不固定,若其他参数值包含code字符串,会导致误判 - 使用
matches匹配空code:matches规则针对的是已存在的参数值,而需求是参数不存在,因此触发非空字符串错误
内容的提问来源于stack exchange,提问作者Júlio Marvim
相关产品推荐
相关产品推荐

