AVEH
AVEH

Reputation: 21

How to add matching rules to a PACT when using a PACT-builder?

Using the PACT-builder for consumer in a consumer-driven test, I try to build a pact and generate the contract as a json file (in a target folder by default).

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "foo-provider")
class FooContract {

   @Pact(consumer = "foo-consumer")
   RequestResponsePact createPact(PactDslWithProvider builder) {
      return builder.given("A server error")
            .uponReceiving("Get all Foos")
            .path("/foos")
            .willRespondWith()
            .status(500)
            .body("{"title":"Internal Server Error"}")
            .toPact()
   }

   @Test
   void getAllFoos(MockServer mockServer) throws IOException, URISyntaxException {
      var HttpResponse response = Request.Get(new URIBuilder(mockServer.getUrl() + "/foos").build()).execute().returnResponse();
      assertThat(response.getStatusLine().getStatusCode()).isEqualTo(500);
   }
}

It results in a file with the following content, excluding the matchingRules-block I would like to get in there:

{
  "provider": {
     "name": "foo-provider"
  },
  "consumer": {
     "name": "foo-consumer"
  },
  "interactions": [
    {
      "description": "A server error",
      "request": {
        "method": "GET",
        "path": "/foos"
      },
      "response": {
        "status": "GET",
        "body": {
          "title": "Internal Server Error"
        },
        "matchingRules": {
           "$.body.title": {
             "match": "type"
           }
        }
      }
    }
  ]
}

Do you know how to include these matching rules in the file? Because, they are supported by the framework, and when added, let's say, manually, the provider-side test-implementation recognizes it and it works.


I use the following dependency/version:

<dependency>
  <groupId>au.com.dius</groupId>
  <artifactId>pact-jvm-consumer-junit5</version>
  <version>4.0.10</version>
  <scope>test</scope>
</dependency>

Upvotes: 2

Views: 1854

Answers (1)

Matthew Fellows
Matthew Fellows

Reputation: 4065

You get matching rules by using matchers. Currently, you're passing a hard coded JSON, so Pact doesn't know which bits should have matchers and which should be tested verbatim.

In your case, that would be something like this:

PactDslJsonBody body = new PactDslJsonBody()
    .stringType("title", "Internal server error");

You can then pass it in like so:

   @Pact(consumer = "foo-consumer")
   RequestResponsePact createPact(PactDslWithProvider builder) {
      return builder.given("A server error")
            .uponReceiving("Get all Foos")
            .path("/foos")
            .willRespondWith()
            .status(500)
            .body(body)
            .toPact()
   }

Upvotes: 1

Related Questions