Skip to main content
A request matcher is the part of an expectation that decides whether an incoming request should trigger the expectation’s action. MockServer supports two matcher types:
  • Request properties matcher — matches by HTTP properties such as method, path, headers, query parameters, cookies, and body
  • OpenAPI matcher — matches against an OpenAPI v3 specification (see OpenAPI)
All string fields in a request properties matcher accept plain strings, Java-style regular expressions, or JSON Schema. Prefix a value with ! (in JSON/REST) or wrap it with not() (in Java) to negate it. Prefix a key with ? to make it optional.

Method

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("GET")
            .withPath("/some/path")
            .withHeaders(
                header("Accept", "application/json"),
                header("Accept-Encoding", "gzip, deflate, br")
            )
    )
    .respond(
        response()
            .withBody("some_response_body")
    );
Use a regex to match multiple methods. To match any method except GET:
request().withMethod(not("GET"))

Path

Match an exact path, a regex, or negate it.
// exact
request().withPath("/some/path")

// regex — matches any path starting with /some
request().withPath("/some.*")

// negated — matches any path that does NOT start with /some
request().withPath(not("/some.*"))

Path parameters

Use {paramName} placeholders in the path and specify values under pathParameters.
new MockServerClient("localhost", 1080)
    .when(
        request()
            .withPath("/some/path/{cartId}")
            .withPathParameters(
                param("cartId", "[A-Z0-9\\-]+")
            )
    )
    .respond(response().withBody("some_response_body"));
Use a JSON Schema value for more complex constraints:
"pathParameters": {
    "cartId": [{ "schema": { "type": "string", "pattern": "^[A-Z0-9-]+$" } }],
    "maxItemCount": [{ "schema": { "type": "integer" } }]
}

Query parameters

new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("GET")
            .withPath("/view/cart")
            .withQueryStringParameters(
                param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092")
            )
    )
    .respond(response().withBody("some_response_body"));
Mark a parameter as optional by prefixing the key with ?:
"queryStringParameters": {
    "?cartId": ["[A-Z0-9\\-]+"],
    "?maxItemCount": [{ "schema": { "type": "integer" } }]
}
By default, query parameter matching uses SUB_SET mode — the request must contain at least one matching value per non-optional key, but may contain additional parameters. Set "keyMatchStyle": "MATCHING_KEY" to require all values for a key to match.

Headers

request()
    .withHeaders(
        header("Accept", "application/json"),
        header("Accept-Encoding", "gzip, deflate, br")
    )
Match headers with regex names or values:
"headers": {
    "Accept.*": [".*gzip.*"]
}
Negate a header value:
"headers": {
    "Accept": ["!application/json"],
    "Accept-Encoding": ["!.*gzip.*"]
}
Require a header to be absent:
"headers": {
    "!Accept": [".*"]
}
Use a JSON Schema to validate a header value:
"headers": {
    "Accept.*": [{ "schema": { "type": "string", "pattern": "^.*gzip.*$" } }]
}
Make a header optional:
"headers": {
    "?X-Optional-Header": ["some-value"]
}

Cookies

Cookies follow the same pattern as headers but map each name to a single value.
request()
    .withCookies(
        cookie("session", "4930456C-C718-476F-971F-CB8E047AB349")
    )
Use a JSON Schema for the cookie value:
"cookies": {
    "session": { "schema": { "type": "string", "format": "uuid" } }
}
Mark a cookie as optional with the ? prefix:
"cookies": {
    "?session": { "schema": { "type": "string", "format": "uuid" } }
}

Body

MockServer supports many body match types.
Match exact body content:
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest": { "body": "some_exact_string" },
  "httpResponse": { "body": "some_response_body" }
}'
Match a substring using subString: true:
"body": {
    "type": "STRING",
    "string": "some_string",
    "subString": true
}
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest": {
    "body": { "type": "REGEX", "regex": "starts_with_.*" }
  },
  "httpResponse": { "body": "some_response_body" }
}'
In Java: .withBody(regex("starts_with_.*"))
Strict matching (all fields, array order, no extra fields):
"body": {
    "type": "JSON",
    "json": { "id": 1, "name": "Scruffles" },
    "matchType": "STRICT"
}
Partial matching — only the fields you specify must be present:
"body": {
    "type": "JSON",
    "json": { "name": "Scruffles" },
    "matchType": "ONLY_MATCHING_FIELDS"
}
Use JSONUnit placeholders to ignore fields or match by type:
"body": {
    "type": "JSON",
    "json": { "id": "${json-unit.any-number}", "name": "${json-unit.ignore-element}" }
}
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest": {
    "body": {
      "type": "JSON_SCHEMA",
      "jsonSchema": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "name": { "type": "string" }
        },
        "required": ["id", "name"]
      }
    }
  },
  "httpResponse": { "body": "some_response_body" }
}'
Matches if at least one value is returned by the expression:
"body": {
    "type": "JSON_PATH",
    "jsonPath": "$.store.book[?(@.price < 10)]"
}
Matches if at least one node is returned by the expression:
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest": {
    "body": {
      "type": "XPATH",
      "xpath": "/bookstore/book[price>30]/price"
    }
  },
  "httpResponse": { "body": "some_response_body" }
}'
In Java: .withBody(xpath("/bookstore/book[price>30]/price"))Negate the XPath match:
"body": { "not": true, "type": "XPATH", "xpath": "/bookstore/book[price>30]/price" }
Exact XML match:
"body": {
    "type": "XML",
    "xml": "<bookstore><book nationality=\"ITALIAN\"><title>Everyday Italian</title></book></bookstore>"
}
Use XMLUnit placeholders to ignore elements or match by type:
"body": {
    "type": "XML",
    "xml": "<bookstore><book><author>${xmlunit.ignore}</author><year>${xmlunit.isNumber}</year></book></bookstore>"
}
"body": {
    "type": "XML_SCHEMA",
    "xmlSchema": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:schema ...>...</xs:schema>"
}
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest": {
    "method": "POST",
    "headers": { "Content-Type": ["application/x-www-form-urlencoded"] },
    "body": {
      "type": "PARAMETERS",
      "parameters": {
        "email": ["joe.blogs@gmail.com"],
        "password": ["secure_Password123"]
      }
    }
  },
  "httpResponse": { "body": "some_response_body" }
}'

Negation

Prefix any string value with ! in JSON/REST to negate it. In Java, wrap it with not():
request().withMethod(not("GET"))
request().withPath(not("/some.*"))
{ "method": "!GET" }
{ "path": "!/some.*" }

OpenAPI matcher

You can also use an OpenAPI v3 specification as the request matcher. See OpenAPI for details.
"httpRequest": {
    "specUrlOrPayload": "https://example.com/openapi.json",
    "operationId": "showPetById"
}