Request Matching

Stef Heyenrath edited this page Sep 1, 2018 · 1 revision

Request Matching

WireMock supports matching of requests to stubs and verification queries using the following attributes:

  • Path/URL
  • HTTP Method
  • Query parameters
  • Headers
  • Cookies
  • Request Body

Matchers

The following paragraphs describe in detail which matchers can be used.

At this moment these matchers are supported:

  • LinqMatcher
  • ExactMatcher
  • WildcardMatcher
  • RegexMatcher
  • XPathMatcher
  • JsonMatcher
  • JsonPathMatcher
  • SimMetricsMatcher

Dynamic Linq (LinqMatcher)

Can be used to match an object using Dynamic Linq (https://github.com/StefH/System.Linq.Dynamic.Core)

C# option

var server = FluentMockServer.Start();
server
    .Given(Request.Create().WithPath("/linq")
        .WithParam("from", new LinqMatcher("DateTime.Parse(it) > \"2018-03-01 00:00:00\"")))
    .RespondWith(Response.Create()
        .WithBody("linq match !!!")
    );

JSON Mapping option

{
    "Guid": "67ae335b-5d79-42dc-8ca7-236280ab91ec",
    "Priority": 0,
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/linq"
                }
            ]
        },
        "Params": [
            {
                "Name": "from",
                "Matchers": [
                    {
                        "Name": "LinqMatcher",
                        "Pattern": "DateTime.Parse(it) > \"2018-03-01 00:00:00\""
                    }
                ]
            }
        ],
        "Body": {}
    },
    "Response": {
        "Body": "linq match !!!"
    }
}

JSON (JsonMatcher)

Checks if a JSON object (or JSON as string) is DeepEqual.

C# option 1

var server = FluentMockServer.Start();
server
    .Given(Request
    .Create()
    .WithPath("/jsonmatcher1")
    .WithBody(new JsonMatcher("{ \"x\": 42, \"s\": \"s\" }"))
    .UsingPost())
    .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
    .RespondWith(Response.Create().WithBody(@"{ ""result"": ""jsonbodytest1"" }"));

JSON Mapping option 1

{
    "Guid": "debaf408-3b23-4c04-9d18-ef1c020e79f2",
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/jsonbodytest",
                    "IgnoreCase": false
                }
            ]
        },
        "Methods": [
            "post"
        ],
        "Body": {
            "Matcher": {
                "Name": "JsonMatcher",
                "Pattern": "{ \"x\": 42, \"s\": \"s\" }"
            }
        }
    },
    "Response": {
        "StatusCode": 200,
        "Body": "{ \"result\": \"jsonbodytest\" }",
        "UseTransformer": false
    }
}

C# option 2

var server = FluentMockServer.Start();
server
    .Given(Request
    .Create()
    .WithPath("/jsonmatcher2")
    .WithBody(new JsonMatcher({ x = 42, s = "s" }))
    .UsingPost())
    .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
    .RespondWith(Response.Create().WithBody(@"{ ""result"": ""jsonbodytest2"" }"));

JSON Mapping option 2

{
    "Guid": "debaf408-3b23-4c04-9d18-ef1c020e79f2",
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/jsonbodytest2",
                    "IgnoreCase": false
                }
            ]
        },
        "Methods": [
            "post"
        ],
        "Body": {
            "Matcher": {
                "Name": "JsonMatcher",
                "Pattern": { "x": 42, "s": "s" }
            }
        }
    },
    "Response": {
        "StatusCode": 200,
        "Body": "{ \"result\": \"jsonbodytest2\" }",
        "UseTransformer": false
    }
}
// matching
{ "x": 1, "s": "s" }

// not matching
{ "x": 2, "s": "x" }

JSON Path (JsonPathMatcher)

Deems a match if the attribute value is valid JSON and matches the JSON Path expression supplied. A JSON body will be considered to match a path expression if the expression returns either a non-null single value (string, integer etc.), or a non-empty object or array.

C#

var server = FluentMockServer.Start();
server
  .Given(
    Request.Create().WithPath("/some/thing").UsingGet()
      .WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"));
  )
  .RespondWith(Response.Create().WithBody("Hello"));

JSON Mapping

{
    "Guid": "e4a600b8-9d6f-453f-90c6-3db2b0885ddb",
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/jsonpath",
                    "IgnoreCase": false
                }
            ]
        },
        "Methods": [
            "put"
        ],
        "Body": {
            "Matcher": {
                "Name": "JsonPathMatcher",
                "Pattern": "$.things[?(@.name == 'RequiredThing')]"
            }
        }
    },
    "Response": {
        "StatusCode": 200,
        "BodyDestination": "SameAsSource",
        "Body": "{ \"result\": \"JsonPathMatcher !!!\"}",
        "UseTransformer": false
    }
}
// matching
{ "things": { "name": "RequiredThing" } }
{ "things": [ { "name": "RequiredThing" }, { "name": "Wiremock" } ] }
// not matching
{ "price": 15 }
{ "things": { "name": "Wiremock" } }

XPath

Deems a match if the attribute value is valid XML and matches the XPath expression supplied. An XML document will be considered to match if any elements are returned by the XPath evaluation. WireMock delegates to XPath2.Net, therefore it support up to XPath version 2.0.

C#

var server = FluentMockServer.Start();
server
    .Given(Request.Create()
        .WithPath("/xpath").UsingPost()
        .WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]"))
    )
    .RespondWith(Response.Create().WithBody("XPathMatcher!"));

JSON Mapping

{
    "Guid": "abc5848e-cedd-42ad-8f58-4ba6df01180f",
    "Priority": 0,
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/xpath",
                    "IgnoreCase": false
                }
            ]
        },
        "Methods": [
            "post"
        ],
        "Body": {
            "Matcher": {
                "Name": "XPathMatcher",
                "Pattern": "/todo-list[count(todo-item) = 3]"
            }
        }
    },
    "Response": {
        "StatusCode": 200,
        "BodyDestination": "SameAsSource",
        "Body": "XPathMatcher!",
        "UseTransformer": false
    }
}

Will match xml below:

<todo-list>
  <todo-item id='a1'>abc</todo-item>
  <todo-item id='a2'>def</todo-item>
  <todo-item id='a3'>xyz</todo-item>
</todo-list>

Regular Expression Matching

The RegexMatcher can be used to match using a regular expression.

var server = FluentMockServer.Start();
server
  .Given(
    Request.Create().WithPath("/reg").UsingPost()
	  .WithBody(new RegexMatcher("H.*o"));
  )
  .RespondWith(Response.Create().WithBody("Hello matched with RegexMatcher"));
// matching
Hello World

// not matching
Hi WM

Similarity Metric Matching

SimMetrics.Net is used as a Similarity Metric Library, e.g. from edit distance's (Levenshtein, Gotoh, Jaro etc) to other metrics, (e.g Soundex, Chapman).

var server = FluentMockServer.Start();
server
  .AllowPartialMatching()
  .Given(
    Request.Create().WithPath("/reg").UsingGet()
	  .WithBody(new SimMetricsMatcher("The cat walks in the street."));
  )
  .RespondWith(Response.Create().WithBody("Matched with SimMetricsMatcher"));
// matching with distance 0.793
The car drives in the street.

// matching with distance 0.071
Hello

WildcardMatching

WildcardMatching is mostly used for Path and Url matching. This matcher allows a ? for a single character and * for any characters.

var server = FluentMockServer.Start();
server
  .Given(Request.Create().WithPath("/some*").UsingGet())
  .RespondWith(Response.Create().WithBody("Hello"));
// matching
Url like /somebody and /someting

Reversing the match behaviour with MatchBehaviour.RejectOnMatch

The default behaviour for Matchers is MatchBehaviour.AcceptOnMatch so that when the matcher processes a request that corresponds with the matcher, the stubbed response is returned. In some scenarios you might want to reverse this behaviour so that the stubbed response is returned with the absence of a match.

e.g. You want to return 401 Unauthorised if the caller does not provide a header containing the API Key:

server
   .Given(Request.Create()
             .WithPath("/needs-a-key")
             .UsingGet()
             .WithHeader("api-key", "*", MatchBehaviour.RejectOnMatch)
             .UsingAnyMethod())
   .RespondWith(Response.Create()
             .WithStatusCode(HttpStatusCode.Unauthorized)
             .WithBody(@"{ ""result"": ""api-key missing""}"));
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.