7

I am trying to create dynamic mocks using WireMock. I have a situation where if I specify URL like :

http://localhost:8089/api/account/abc@abc.com

then I should receive response like:

{ 
  "account" : "abc@abc.com" 
}

In brief, the path param is returned in the response body. I am able to make the request URL generic by using urlPathPattern set to /api/account/([a-z]*) however, I am not sure how should I capture abc@abc.com and return this in the response using regular expressions.

A. Kootstra
  • 6,827
  • 3
  • 20
  • 43
JavaMan
  • 465
  • 1
  • 6
  • 21

2 Answers2

12

In WireMock the regular expressions can be used to recognize the email format in the Request Matching. For the purpose of this example I used a very crude example. Your production implementation may require a more robust approach.

This request:

http://localhost:8181/api/account/someone@somewhere.net

Is matched by this rule:

{
    "request": {
        "method": "GET",
        "urlPathPattern": "/api/account/([a-z]*@[a-z]*.[a-z]*)"
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "account": "{{request.path.[2]}}"
        },
        "transformers": ["response-template"],
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

And returns this response:

{
  "account": "someone@somewhere.net"
}

It makes use of a Response Template processing functionality in WireMock. The Request Model variables [{{request.path.[2]}}] can be used to obtain sections from the request.

A. Kootstra
  • 6,827
  • 3
  • 20
  • 43
  • Thanks a lot @A. Kootstra for responding to my question. The solution outlined by yourself has worked for me and I am now building more complex tests. Awesome, Cheers mate !!! – JavaMan Nov 19 '18 at 01:16
  • 1
    Nice answer! This snippet may also save some search time: `WireMockServer wireMockServer = new WireMockServer(options()..extensions(new ResponseTemplateTransformer(true)))` – Bohemian Jun 25 '20 at 01:34
1

The same can be done using WireMock.Net - Response-Templating

The rule looks like:

{
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "RegexMatcher",
                    "Pattern": "^/api/account/([a-z]*@[a-z]*.[a-z]*)$"
                }
            ]
        },
        "Methods": [
            "get"
        ]
    },
    "Response": {
        "StatusCode": 200,
        "BodyAsJson": {
            "account": "{{request.PathSegments.[2]}}"
        },
        "UseTransformer": true,
        "Headers": {
            "Content-Type": "application/json"
        }
    }
}
Stef Heyenrath
  • 9,335
  • 12
  • 66
  • 121