如何实现调用/transform时触发含Wiremock响应体ID的Mock Webhook
WireMock Webhook无法提取响应ID的解决方法
问题场景
需要实现Mock Webhook:当/transform接口被调用时触发Webhook,且Webhook请求体需从WireMock响应体中获取id值。已启用body-transformer转换器,但按以下配置无法提取id:
原配置代码
{ "request": { "method": "POST", "urlPath": "/transform" }, "response": { "status": 200, "body": "{\"message\": \"success\", \"id\": \"{{randomValue length=10 type='ALPHANUMERIC'}}\"}", "headers": { "Content-Type": "application/json" } }, "serveEventListeners": [ { "name": "webhook", "parameters": { "method": "POST", "url": "https://webhook.site/9c32fadb-b542-4edf-a530-85a012064566", "headers": { "Content-Type": "application/json" }, "body": "{\"id\": \"{{jsonPath response.body '$.id'}}\"}" } } ] }
转换器配置
"transformers":[ "body-transformer" ]
问题原因
response.body是响应生成后的最终字符串,Webhook的模板解析时机早于响应体的动态变量替换,导致jsonPath无法读取到生成的id值。body-transformer主要负责请求/响应的内容转换,对Webhook参数的模板解析支持有限。
解决方案
通过场景变量存储生成的id,让响应体和Webhook共享同一个变量值:
修正后的完整配置
{ "request": { "method": "POST", "urlPath": "/transform" }, "response": { "status": 200, "body": "{\"message\": \"success\", \"id\": \"{{randomValue length=10 type='ALPHANUMERIC' var='generatedId'}}\"}", "headers": { "Content-Type": "application/json" } }, "serveEventListeners": [ { "name": "webhook", "parameters": { "method": "POST", "url": "https://webhook.site/9c32fadb-b542-4edf-a530-85a012064566", "headers": { "Content-Type": "application/json" }, "body": "{\"id\": \"{{generatedId}}\"}" } } ], "transformers": ["body-transformer"] }
关键修改点
- 在
randomValue指令中添加var='generatedId',将生成的随机ID存入场景变量generatedId - 响应体中的
id直接引用该变量,保证响应内容和Webhook使用的ID一致 - Webhook的请求体直接通过
{{generatedId}}调用变量,无需再解析响应体
注意事项
确保WireMock版本不低于2.27.0(该版本开始支持场景变量的存储与引用),且body-transformer扩展已正确加载。
内容的提问来源于stack exchange,提问作者koko chambo
相关产品推荐
相关产品推荐

