How to verify stringified json in pact

802 Views Asked by At

I am trying to build a pact between two services using asynchronous communication.

This is the code I used for generate the pact:

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "provider", providerType = ProviderType.ASYNCH)
public class StringifiedPactTest {

    @Pact(consumer = "consumer", provider = "provider")
    public MessagePact generatePact(MessagePactBuilder builder) {
        return builder.hasPactWith("provider")
                .expectsToReceive("A valid aws sns event")
                .withContent(new PactDslJsonBody().stringType(new String[]{"MessageId", "TopicArn"}).stringValue("Message", new PactDslJsonBody().stringType("Value", "Foo").toString()))
                .toPact();
    }

    @Test
    @PactTestFor(pactMethod = "generatePact")
    public void buildPact(List<Message> messages) {

    }
}

And the generated pact is

{
  "consumer": {
    "name": "consumer"
  },
  "provider": {
    "name": "provider"
  },
  "messages": [
    {
      "description": "A valid aws sns event",
      "metaData": {
        "contentType": "application/json"
      },
      "contents": {
        "TopicArn": "string",
        "Message": "{\"Value\":\"Foo\"}",
        "MessageId": "string"
      },
      "matchingRules": {
        "body": {
          "$.MessageId": {
            "matchers": [
              {
                "match": "type"
              }
            ],
            "combine": "AND"
          },
          "$.TopicArn": {
            "matchers": [
              {
                "match": "type"
              }
            ],
            "combine": "AND"
          }
        }
      }
    }
  ],
  "metadata": {
    "pactSpecification": {
      "version": "3.0.0"
    },
    "pact-jvm": {
      "version": "4.0.10"
    }
  }
}

This means the producer should have a "Message" that matches {"Value" : "Foo"}, any other combination like {"Value" : "Bar" } won't be successful. Is there any way to add matching rules inside a stringified json? Thanks!

2

There are 2 best solutions below

0
On

Here's an anonymised example from a test we have. Hope it's useful. This creates a pact that matches only on type. So on the provider side, when I test against the contract, it doesn't matter what value I have for categoryName for example, as long as it's a stringType:

@PactTestFor(providerName = "provider-service", providerType = ProviderType.ASYNCH)
public class providerServiceConsumerPactTest {

    private static String messageFromJson;

    @BeforeAll
    static void beforeAll() throws Exception {
        messageFromJson = StreamUtils.copyToString(new ClassPathResource("/json/pact/consumer-service_provider-service.json").getInputStream(), Charset.defaultCharset());

    }

    @Pact(provider = "provider-service", consumer = "consumer-service")
    public MessagePact providerServiceMessage(MessagePactBuilder builder) {
        DslPart body = new PactDslJsonBody()
            .object("metaData")
                .stringType("origin", "provider-service")
                .datetimeExpression("dateCreated", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .closeObject()
            .minArrayLike("categories", 0, 1)
                .stringType("id", "example data")
                .stringType("categoryName", "example data")
                .booleanType("clearance", false)
                .closeObject()
            .closeArray();

        return builder
                .expectsToReceive("a provider-service update")
                .withContent(body)
                .toPact();
    }

    @Test
    @PactTestFor(pactMethod = "providerServiceMessage")
    public void testProviderServiceMessage(MessagePact pact) {

        // State

        final String messageFromPact = pact.getMessages().get(0).contentsAsString();

        // Assert

        JSONAssert.assertEquals(messageFromPact, messageFromJson, false);
    }
0
On

I'm having exactly the same issue, and unfortunately I don't think it's possible to tell Pact to parse the stringified JSON and look inside it (e.g. to verify that parse(Message).Value === "Foo" in your example).

The best you can do is write a regular expression to match the string you're expecting. This kind of sucks because there's no easy way to ignore the ordering of the JSON keys (e.g. "{\"a\":\"1\", \"b\":\"2\"}" and "{\"b\":\"2\", \"a\":\"1\"}" will compare different) but AFAIK Pact simply lacks the parsing functionality we're looking for, so the only tool it provides is regex.