Show List

Advanced configuration of Wiremock

WireMock can be configured to respond to dynamic requests by creating complex response templates and using placeholders and variables in the response body. This allows you to generate responses that are tailored to specific requests, and can be useful in a variety of testing and development scenarios. Here's an overview of how to configure WireMock to respond to dynamic requests using response templates:

  • First, create a new mapping in your mappings.json file that defines the request you want to respond to. For example:
json
Copy code
{ "request": { "method": "GET", "url": "/users", "queryParameters": { "name": { "equalTo": "john" } } }, "response": { "status": 200, "body": "Hello, {{request.query.name.first}} {{request.query.name.last}}!" } }

This mapping defines a GET request to the URL /users with a query parameter named "name" that has a value of "john". The response to this request will have a status code of 200 and a body that includes the values of the "first" and "last" properties of the "name" query parameter, as defined by the placeholders {{request.query.name.first}} and {{request.query.name.last}}.

  • To create more complex response templates, you can use the Handlebars templating language, which is supported by WireMock. For example, you could create a response that includes a list of users:
swift
Copy code
{ "request": { "method": "GET", "url": "/users" }, "response": { "status": 200, "body": "{{#each users}}\n- {{this}}\n{{/each}}" } }

This mapping defines a GET request to the URL /users. The response to this request will have a status code of 200 and a body that includes a list of users, as defined by the {{#each users}} and {{this}} Handlebars tags.

  • You can also use placeholders and variables in the response headers and status codes. For example, you could create a mapping that responds with a status code based on the value of a query parameter:
css
Copy code
{ "request": { "method": "GET", "url": "/status", "queryParameters": { "code": { "matches": "2\\d\\d" } } }, "response": { "status": "{{request.query.code}}", "headers": { "Content-Type": "text/plain" }, "body": "Status code: {{request.query.code}}" } }

This mapping defines a GET request to the URL /status with a query parameter named "code" that must match the regular expression 2\\d\\d. The response to this request will have a status code that matches the value of the "code" query parameter, as defined by the {{request.query.code}} placeholder.

By using response templates and placeholders in this way, you can create mock services that are more flexible and more closely mimic real-world APIs and services, making it easier to develop and test your applications.


    Leave a Comment


  • captcha text