MockServer verify with multiple body matchers

3.4k Views Asked by At

I'm using MockServer body matchers to verify an endpoint request's body parameters. Some properties can be matched exactly, but others may need a separate subString or regex matcher, because part of that property is unknown. For example, a date-time string may have a known date, but unknown time.

However, with multiple withBody() calls, the verify method passes if one or more matcher passes. How to implement a logical AND instead of an OR?

mockServer.verify(
    request()
        .withPath(url)
        .withMethod("POST")
        .withBody(
            json(
                "{\"firstName\": \"foo\",\"lastName\": \"bar\"}",
                MatchType.ONLY_MATCHING_FIELDS))
        .withBody(
            // Need subString because we don't know the time and only want to validate the date
            subString("\"order_date_time\": \"2021-04-15")));
1

There are 1 best solutions below

0
On BEST ANSWER

To perform a logical-AND on multiple body matcher criteria, you need to call the verify() method multiple times:

private void verifyOrderPlaced() {
  verifyName();
  verifyOrderDate();
}

private void verifyName() {
  mockServer.verify(
      request()
          .withPath(url)
          .withMethod("POST")
          .withBody(
              json(
                  "{\"firstName\": \"foo\",\"lastName\": \"bar\"}",
                  MatchType.ONLY_MATCHING_FIELDS)));
}

private void verifyOrderDate() {
  mockServer.verify(
      request()
          .withPath(url)
          .withMethod("POST")
          .withBody(
              subString("\"order_date_time\": \"2021-04-15")));
}