Show List

Working with request matching in Wiremock

WireMock uses a request matching algorithm to determine which response to return for incoming HTTP requests. The default request matching behavior is to match on the HTTP method, URL, headers, query parameters, and request body (if present). However, WireMock also provides advanced matching rules that can be used to create more specific matching criteria. Here's an overview of how WireMock matches incoming requests to responses and how to configure advanced matching rules:

  1. Default matching behavior: When a request is received by WireMock, it first checks the mappings.json file for a matching request pattern. The default request matching behavior is to match on the HTTP method, URL, headers, query parameters, and request body (if present). If a matching pattern is found, WireMock returns the corresponding response.

  2. Advanced matching rules: WireMock also provides advanced matching rules that can be used to create more specific matching criteria. These include:

    • Regex matching: You can use regular expressions to match on any part of the request, including the URL, headers, query parameters, and request body. For example, you could create a mapping that matches any request with a URL that ends in ".json":
swift
Copy code
{ "request": { "urlPattern": ".*\\.json" }, "response": { "status": 200, "body": "This is a JSON response" } }
  • Custom matchers: You can create your own custom matchers to match on specific parts of the request. Custom matchers are implemented using Java code, and can be added to WireMock as plugins. For example, you could create a custom matcher that matches on the presence of a specific header:
typescript
Copy code
public class HeaderMatcher extends CustomMatcher<String> { private String headerName; private String headerValue; public HeaderMatcher(String headerName, String headerValue) { super("matchesHeader"); this.headerName = headerName; this.headerValue = headerValue; } @Override public boolean matches(Object o) { Request request = (Request) o; return headerValue.equals(request.getHeader(headerName)); } } // Then, in your mapping: { "request": { "customMatcher": "matchesHeader", "headerName": "X-Custom-Header", "headerValue": "someValue" }, "response": { "status": 200, "body": "This is a custom header response" } }

These are just a few examples of the advanced matching rules that WireMock provides. By using these rules, you can create mock services that are more specific and more closely mimic real-world APIs and services, making it easier to develop and test your applications.


    Leave a Comment


  • captcha text