'Returning responses randomly from wiremock

I need to return a random response out of a predefined set each time the same wiremock endpoint is called. How can I do it?



Solution 1:[1]

This can be achieved by using Response Templating (please see the official documentation for more information). I will assume that you are using Wiremock Standalone. The first thing that you need to do is to enable response templating, so you need to run Wiremock using --global-response-templating option. For example:

java -jar wiremock-standalone-2.27.2.jar --global-response-templating

Please note that you can also use local templating (if you want to configure templating only for a specific mock) using the option --local-response-templating

The next thing is to create a mock that uses Handlebar bars helpers, in your case you can generate a random string like this:

    {
    "request": {
        "urlPath": "/templated"
    },
    "response": {
        "body": "{{randomValue length=33 type='ALPHANUMERIC'}}",
        "transformers": ["response-template"],
        "status" : 200
    }
}

That's it. Every time that you call /templated resource you should get a different alphanumeric string. Again you can have a look to the documentation under "Random value helper" section to see which helper suits you better.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1