MockServer 使用多个 body 匹配器进行验证

MockServer verify with multiple body matchers

我正在使用 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 匹配器,因为 属性 的一部分是未知的。例如,date-time 字符串可能具有已知日期,但未知时间。

但是,对于多个 withBody() 调用,如果一个或多个匹配器通过,verify 方法就会通过。如何实现逻辑 AND 而不是 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")));

要对多个正文匹配条件执行逻辑与,您需要多次调用 verify() 方法:

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")));
}