pactpact-jvmpact-java

PactDslJsonArray root level arrays that match all items


I can successfully use PactDslJsonArray.arrayMaxLike(3,3) to create a pact that validates a maximum of 3 items returned.

"body": [
{
    "firstName": "first",
    "lastName": "last",
    "city": "test",
},
{
    "firstName": "first",
    "lastName": "last",
    "city": "test",
},
{
    "firstName": "first",
    "lastName": "last",
    "city": "test",
}
]


"body": {
"$": {
    "matchers": [
        {
            "match": "type",
            "max": 3
        }
    ]
...

However, I would like to reuse the body from another request without the need to specify the attributes again.

DslPart body = new PactDslJsonBody()
    .stringType("firstName","first")
    .stringType("lastName","last")
    .stringType("city", "test")

What I'm looking for is something like :

PactDslJsonArray.arrayMaxLike(3,3).template(body)

instead of

PactDslJsonArray.arrayMaxLike(3,3)
  .stringType("firstName","first")  
  .stringType("lastName","last")  
  .stringType("city", "test")

Thanks

Dan


Solution

  • The point of the DSL is to do validations of the Pact interactions in code. Using a template kinda goes against that concept. What I would recommend is that if you have the same interactions in multiple places, then adding a shared function to add said interaction would be the best way to do so. For example:

    private void personalDetailInteraction(DslPart part) {
       return part.stringType("firstName","first")
        .stringType("lastName","last")
        .stringType("city", "test");
    }
    
    private void yourTest() {
        personalDetailInteraction(
            PactDslJsonArray.arrayMaxLike(3,3)
        )
        .stringType("blarg", "weee")
        ...
    }
    

    If it needs to be shared across different classes, create a InteractionUtils class that can be shared across. This is the best way to do it in my opinion because the compiler makes sure no mistakes are made while creating the interactions, which is kind of the point of the whole framework; to reduce human error.