如何在WireMock中为请求、响应追加参数并发送请求至指定路径?
Hey there! Let me break down exactly how to add headers/cookies to requests (and forward them to a target path) plus modify responses in WireMock—this stuff is really flexible once you know the tricks.
WireMock lets you tweak incoming requests before proxying them to your target API. You can use built-in tools for quick changes or custom logic for more control.
Option 1: Built-in Transformers (Quick & Simple)
For basic header/cookie additions, use WireMock's proxy feature with transformer parameters. Here's how it works with the Java DSL:
stubFor(post(urlEqualTo("/your-incoming-endpoint")) .willReturn(aResponse() // Forward the modified request to your target path .proxiedFrom("https://your-target-api.com/desired-path") // Use transformers to add headers/cookies .withTransformers("request-header-transformer", "request-cookie-transformer") // Define the header to add .withTransformerParameter("add-header-X-Custom-Header", "MyCustomHeaderValue") // Define the cookie to add .withTransformerParameter("add-cookie-Session-ID", "abc123xyz789") ) );
If you're using WireMock standalone with JSON stubs, the config looks like this:
{ "request": { "url": "/your-incoming-endpoint", "method": "POST" }, "response": { "proxyBaseUrl": "https://your-target-api.com/desired-path", "transformers": ["request-header-transformer", "request-cookie-transformer"], "transformerParameters": { "add-header-X-Custom-Header": "MyCustomHeaderValue", "add-cookie-Session-ID": "abc123xyz789" } } }
Option 2: Custom Request Transformers (Full Control)
For conditional logic (like adding headers only if a certain request parameter exists), build a custom transformer:
public class CustomRequestEnhancer extends RequestTransformer { @Override public Request transform(Request request, Parameters parameters) { RequestBuilder requestBuilder = RequestBuilder.update(request); // Add a custom environment header requestBuilder.header("X-Environment", "staging"); // Add a cookie with extra attributes (path/domain) requestBuilder.addCookie(Cookie.builder("AuthToken", "s3cr3t-t0k3n") .path("/") .domain("your-app.com") .build()); return requestBuilder.build(); } @Override public String getName() { return "custom-request-enhancer"; } } // Register the transformer with your WireMock server WireMockServer wireMockServer = new WireMockServer( wireMockConfig().extensions(new CustomRequestEnhancer()) ); wireMockServer.start(); // Use it in your stub stubFor(get(urlEqualTo("/your-endpoint")) .willReturn(aResponse() .proxiedFrom("https://your-target-api.com/target-path") .withTransformers("custom-request-enhancer") ) );
Whether you're returning a stubbed response or modifying a proxied one, WireMock makes it easy to add headers, cookies, or update the response body.
1. Adding Response Headers & Cookies
For basic stubbed responses, attach headers and cookies directly via the Java DSL:
stubFor(get(urlEqualTo("/your-endpoint")) .willReturn(aResponse() .withStatus(200) // Add a response metadata header .withHeader("X-Response-Metadata", "Generated-by-WireMock") // Add a cookie with expiry attributes .withCookie("Session-Expiry", "2024-12-31", ResponseCookie.builder().path("/").maxAge(31536000).build()) // Your response body .withBody("{\"status\": \"success\", \"data\": []}") ) );
In JSON stub format:
{ "request": { "url": "/your-endpoint", "method": "GET" }, "response": { "status": 200, "headers": { "X-Response-Metadata": "Generated-by-WireMock", "Set-Cookie": "Session-Expiry=2024-12-31; Path=/; Max-Age=31536000" }, "body": "{\"status\": \"success\", \"data\": []}" } }
2. Modifying Response Body Parameters
To add or update fields in a response body (like adding a trace ID to a proxied API response), use a custom response transformer:
public class CustomResponseModifier extends ResponseTransformer { @Override public Response transform(Request request, Response response, Parameters parameters) { // Parse the original response body String originalBody = response.getBodyAsString(); JSONObject responseJson = new JSONObject(originalBody); // Add a new trace ID parameter responseJson.put("trace-id", UUID.randomUUID().toString()); // Update an existing status field responseJson.put("status", "mock-success"); // Build the modified response return ResponseBuilder.update(response) .body(responseJson.toString()) .build(); } @Override public String getName() { return "custom-response-modifier"; } } // Register and use the transformer wireMockServer = new WireMockServer( wireMockConfig().extensions(new CustomResponseModifier()) ); stubFor(get(urlEqualTo("/proxied-endpoint")) .willReturn(aResponse() .proxiedFrom("https://external-api.com") .withTransformers("custom-response-modifier") ) );
Hope these examples cover what you need! WireMock's transformer system is super powerful for tweaking requests and responses to match your testing needs.
内容的提问来源于stack exchange,提问作者GOKUL ANANTH NKP

