Wiremock Stand alone - How to manipulate response with request data

Sam picture Sam · Mar 28, 2017 · Viewed 10.4k times · Source

I was trying to implement mocking of POST REST call using Wiremock Standalone server. I am faced with a challenge like this, suppose the post body contains an "name" field and its value, the same value should be returned in the response of that POST call. My json file looks like this:

{
"priority": 1,
"request": {
    "method": "POST",
    "urlPath": "/primeSlots",
    "bodyPatterns" : [ {
        "matchesJsonPath" : "{ \"things\": [ { \"name\": \"794363\" }] 
 }"
    } ]
 },
 "response": {
    "status": 200,
    "body": "{{$.things.name.value}}",
    "transformers": ["response-template"]
 }
}

so, I need to get the value , that is 794363,but using above approach not able to get it in the post response body.

I tried this too:

{
 "request": {
    "method": "POST",
    "urlPath": "/transform",
    "bodyPatterns": [
        {
            "matchesJsonPath" : "$.things[?(@.name =~ /[0-9]+/i)]"
        }
    ]
  },
  "response": {
    "status": 200,
    "body": "{\"responseName\": \"
   {{request.body.things.name.value}}\"}",
    "headers": {
        "Content-Type": "application/json"
    },
    "transformers": ["body-transformer"]
  }
 }

So my question is, even if i use a regEx, which matches with any number that comes in the request, how to give back the same number in the response using Wiremock standalone json file? Thanks.

Answer

Tom picture Tom · Mar 29, 2017

Unfortunately WireMock's response templating transformer doesn't currently break out the request body into a Map as would be necessary for what you're trying to do. The request body is just a single string.

The simplest way for you to enable this would probably be to write a Handlebars helper that implements JSONPath or some other mechanism for querying a JSON document, then registering this with the templating transformer when you initialise WireMock.

At some point I'll write handlebars helpers to do this kind of thing for XML and JSON, but that won't be for a while.