能否配置WireMock JSON存根在端点被命中时运行自定义脚本?
Great question—adding side effects when a specific WireMock endpoint is hit is a common and totally valid use case. Let me walk you through the main ways to pull this off, including passing the endpoint as a parameter to your script:
1. Use PostServe Actions (Built-In, No Extra Setup)
WireMock has a built-in feature called postServe actions that lets you run custom logic after a response is sent to the client. This is perfect for side effects like logging, triggering external processes, or updating state.
You can define a Groovy script directly in your JSON stub, and access the incoming request details (including the endpoint URL) via the request object. Here's a working example:
{ "request": { "method": "GET", "url": "/api/your-endpoint" }, "response": { "status": 200, "body": "Request processed" }, "postServeActions": [ { "name": "script", "parameters": { "script": "def hitEndpoint = request.url; println('Endpoint ' + hitEndpoint + ' was accessed'); // Add your custom logic here: call an API, write to a file, etc." } } ] }
- The
request.urlvariable gives you the full endpoint that was hit (you can parse it to extract paths or query params if needed). - Groovy is the default scripting language, but you can configure WireMock to use others like JavaScript if needed.
- This script runs asynchronously by default, so it won't slow down the response sent to the client.
2. Build a Custom Extension (For Complex Logic)
If your side effect requires more complex code (like integrating with external services, using Java libraries, or reusable logic), you can create a custom WireMock extension:
- Write a Java class that implements the
PostServeActioninterface. You'll get access to theRequestobject (which includes the endpoint) and can execute your custom logic. - Package the extension as a JAR and add it to WireMock's classpath.
- Reference the extension in your JSON stub:
{ "request": { "method": "POST", "url": "/api/complex-endpoint" }, "response": { "status": 201, "body": "Created" }, "postServeActions": [ { "name": "my-custom-side-effect", "parameters": { "targetEndpoint": "${request.url}" } } ] }
Your custom extension can then read the targetEndpoint parameter and run whatever logic you need.
Quick Note on Response Configuration Options
You're right that the full list of response-related configs can feel scattered in the docs. For reference, beyond basic status/body/headers, you can also use:
transformersto modify responses dynamicallyfaultto simulate errors (e.g., connection reset)fixedDelayMillisecondsto add latencyheadersto set custom response headers
内容的提问来源于stack exchange,提问作者Andrew Allaire

