WireMock匹配路径无对应返回文件时实现自定义404响应问询
可以实现,以下是两种常用的实现方案:
方案一:单Mapping模板判断(适用WireMock 2.31+版本)
首先确保WireMock启动时已开启响应模板能力(添加启动参数--global-response-templating,或在单个Mapping中单独指定transformers),调整你的现有Mapping配置如下:
{ "mappings": [ { "name": "Retrieve Items", "request": { "headers": { "accept": { "caseInsensitive": true, "equalTo": "application/json" } }, "method": "GET", "urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}" }, "response": { "transformers": ["response-template"], "failOnMissingBodyFile": false, "body": "{% set itemFile = 'items-api/responses/retrieve/' ~ request.pathSegments.[2] ~ '.json' %}{% if fileExists(itemFile) %}{{ readBodyFile(itemFile) }}{% else %}{\n \"timestamp\": {{ now }},\n \"status\": 404,\n \"error\": \"Not Found\",\n \"message\": null,\n \"path\": \"{{ request.path }}\"\n}{% endif %}", "headers": { "content-type": "application/json" }, "status": "{% set itemFile = 'items-api/responses/retrieve/' ~ request.pathSegments.[2] ~ '.json' %}{% if fileExists(itemFile) %}200{% else %}404{% endif %}" } } ] }
配置说明:
failOnMissingBodyFile: false:要求WireMock找不到指定响应文件时不要直接返回默认错误提示,继续执行模板渲染- 内置函数
fileExists会判断__files目录下对应UUID的JSON文件是否存在 - 响应状态码和响应体都会根据文件是否存在动态渲染,匹配你需要的返回逻辑
方案二:双Mapping优先级兜底(兼容所有支持响应模板的WireMock版本)
如果使用的WireMock版本较低不支持fileExists语法,可以通过两个不同优先级的Mapping实现:
{ "mappings": [ { "name": "Retrieve Items - Exists", "priority": 1, "request": { "headers": { "accept": { "caseInsensitive": true, "equalTo": "application/json" } }, "method": "GET", "urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}" }, "response": { "bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json", "transformers": ["response-template"], "headers": { "content-type": "application/json" }, "status": 200 } }, { "name": "Retrieve Items - Not Found", "priority": 10, "request": { "headers": { "accept": { "caseInsensitive": true, "equalTo": "application/json" } }, "method": "GET", "urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}" }, "response": { "transformers": ["response-template"], "jsonBody": { "timestamp": "{{ now }}", "status": 404, "error": "Not Found", "message": null, "path": "{{ request.path }}" }, "headers": { "content-type": "application/json" }, "status": 404 } } ] }
配置说明:
- 优先级数值越小,Mapping匹配优先级越高
- 请求会先匹配优先级为1的Mapping,如果对应UUID的JSON文件存在,直接返回200和文件内容
- 如果文件不存在,优先级为1的Mapping会匹配失败,WireMock会继续匹配更低优先级的Mapping,最终命中第二个配置返回自定义404结构
内容的提问来源于stack exchange,提问作者user4695271
相关产品推荐
相关产品推荐

