Search code examples
wiremockspring-cloud-contract

Using Spring Cloud Contract Groovy DSL, how can I parameterize the response to include values from the request?


I am using Spring Cloud Contract to create stubs for a REST service so I can test with a REST client. I have the stub runner working within a Spring Boot application, and it all works as expected. The problem I am having is that I'd like to see elements of the requests in the responses, to better simulate the eventual behavior of the REST service. For example, in this contract, I'd like what is passed in the "code" field in the request to appear regurgitated in the response:

package contracts

org.springframework.cloud.contract.spec.Contract.make {
    request {
        method('POST')
        url $("/resource")
        body ([
                code : $(client(regex('[a-zA-Z0-9]{5,32}')))
        ])
    }

    response {
        status 200
        body([
                code: ???
        ])
    }
}

Obviously the input "code" can be anything that matches the regular expression, and so the actual value is unknown until runtime. Is there anything i can put in place of "???" to return the code submitted in the request ? I tried accessing, for example:

request.body.serverValue['code']

but that value it seems is generated at compile time, perhaps to enable the auto-generation of tests in ContractVerifierTest.java under generated-test-sources.

Can this be done ? Is this an appropriate use of Spring Cloud Contract ?


Solution

  • Currently, it's not supported. We prefer an approach where you have simpler contracts. If you need in a response a value from the request just hard code both the request and the response parts of the contract.

    You can, however, file an issue and we can try to think of something in the future releases.

    UPDATE:

    With version 1.1.0 that's already possible. Check out the docs for more info - http://cloud.spring.io/spring-cloud-static/spring-cloud-contract/1.1.0.RELEASE/#_referencing_request_from_response