Search code examples
pactpact-jvm

How to represent responses with heterogenous arrays in pact-jvm


I'm having trouble figuring out how to represent arrays with structurally different objects in an array in pact contracts.

From pact-spec-v3

It would also be required to define whether the matchers should be combined with logical AND (all matchers must match) or OR (at least one matcher must match). AND should be the default, but there are cases where an OR makes sense

Can this be leveraged to 'OR' the two different types of objects ?

This is the response that I'm trying to model via the pact-jvm DSL, the suggestions array contains two objects of different types, '1' and '3', having different schemas -

{
  "suggestions": [
    {
      "display_name": "Potato",
      "type": 1,
      "keyword": "Potato",
      "category_l1": {
        "icon_image_url": "XXXXX",
        "id": 1489,
        "name": "Potato"
      }
    },
    {
      "type": 3,
      "suggestion": {
        "display_name": "New Potato (Aloo)",
        "name": "New Potato"
      }
    }
  ]
}

Code that I have so far:

private DslPart getBody() {
    return new PactDslJsonBody()
            .eachLike("suggestions", 1)
                    .stringType("display_name")
                    .integerType("type")
                    .stringType("keyword")
                    .object("category_l1")
                        .stringType("icon_image_url")
                        .stringType("name")
                        .integerType("id")
                    .closeObject()
                    .closeObject()
            .closeArray();
}

Solution

  • This is not currently easy to model with Pact, it works assuming each item is similar to a provided example. For a discussion, see https://github.com/pact-foundation/pact-specification/issues/38