spring-cloud-contract icon indicating copy to clipboard operation
spring-cloud-contract copied to clipboard

Unable to generate dynamic array in response

Open lality90 opened this issue 2 months ago • 1 comments

I have a scenario where if a request has 1 element in the array then return 1 object in response and similarly if the request has n elements respond with n objects, But I am unable to create such a response.

Contract package contracts

import org.springframework.cloud.contract.spec.Contract

Contract.make {
    name("test-multiple-array")
    inProgress()
    request {
        method(POST())
        urlPath('/create')
        headers {
            header('Content-Type', 'application/json')
        }

        bodyMatchers {
            jsonPath('$.id', byEquality())
            jsonPath('$.address', byType {
                minOccurrence(1)
                maxOccurrence(5)
            })
        }

        body([
                id                  : '1',
                address      : [
                        '123 Office',
                        '234 Home'
                ]
        ])
    }
    response {
        status(OK())
        headers {
            contentType applicationJson()
        }

        body([results: [
                {
                    def results = []

                    fromRequest().body('address').each { add ->
                        def resultObject = [
                                processStatus: 'CREATED',
                                address: "${add}"
                        ]
                        results.add(resultObject)
                    }
                    return results
                }()
        ]])
        bodyMatchers {
            jsonPath('$.results', byType())
        }
    }
}

//Expected Response

{
    "results": [
        {
            "processStatus": "CREATED",
            "address": "123 Office"
        },
        {
            "processStatus": "CREATED",
            "address": "234 Home"
        }
    ]
}

//Actual Response

{
    "results": [
        {
            "processStatus": "CREATED",
            "address": [
                "123 Office",
                "234 Home"
            ]
        }
    ]
}

lality90 avatar May 14 '24 15:05 lality90