javamockingwiremock

Wiremock - Grab a string from the URL, modify it and return it as part of the body


I'm working on some load test scenarios at work and I'm having some issues figuring out how to do this with Wiremock.

It's basically this. I have a piece of code that makes a GET to an endpoint that looks something like /api/1/external/client/1234%12LT and I want to grab the last part, strip everything after the % (included) and only return the numbers before it as part of a very simple JSON {"id": "1234"}.

I've been reading about the Response Templating and enabled it on my standalone instance by passing the flag --global-response-templating on the command line. I think it works because if I set it to return a random value using something like {{randomValue length=10 type='NUMERIC'}} it actually returns a random number.

I think I should be using a combination of request.requestLine.pathSegments.[4] to get the last segment of the URL then use the regular expression extractor {{regexExtract request.body '[A-Z]+'}}" (not the actual code, example is taken from documentation) to get the first numerical part but haven't managed to make it work yet.

My mocking code looks something like this:

{
  "request": {
    "urlPattern": "/api/1/example/endpoint/.*",
    "method": "GET"
  },
  "response": {
    "status": "200",
    "headers": {
      "Content-Type": "application/json; charset=utf-8"
    },
    "jsonBody": {
      "id": "{{request.requestLine.pathSegments.[4]}}"
    }
  }
}

Could anyone point me to where I'm screwing up?.

And another question, how do you debug this usually? I've gone over the docs and not sure how to print info to the logs to see if the substitution I'm trying to do is actually working or if what is reaching the endpoint is what I'm assuming should be getting.

Thanks.


Solution

  • Given that you start your WireMock instance with the global reponse templating switched on, then with the following mapping:

    {
      "request": {
        "urlPattern": "/api/1/external/client/.*",
        "method": "GET"
      },
      "response": {
        "status": "200",
        "headers": {
          "Content-Type": "application/json; charset=utf-8"
        },
        "jsonBody": {
          "id": "{{regexExtract request.requestLine.pathSegments.[4] '[0-9]*'}}"
        }
      }
    }
    

    Given the following URL:

    http://localhost:8080/api/1/external/client/1234%12LT
    

    The response will be:

    {
        "id": "1234"
    }