Search code examples
spring-cloud-contract

Should Spring Cloud Contracts be concrete or flexible?


There are 2 styles of writing contracts used in our project. First is to save both request and response as json files and use them to define a contract:

request {
    body(file("request.json"))
}
response {
    body(file("response.json"))
}

It creates stubs, that don't work unless your request is filled exactly like request.json, which makes it difficult to write unit tests with stubs for the consumer. However, using concrete values might be better for testing integration.

The second approach is to use regular expressions as much as possible:

request {
    body([
        clientName: $(anyNonBlankString()),
        accountNumber: $(consumer(regex("[0-9]{20}")), producer("12345678901234567890")),
        amount: $(anyNumber())
    ])
}

Stubs defined this way will be flexible, but we end up testing only presence of fields in the request and their format.

Which is the right way to write a contract?


Solution

  • It depends only on what you prefer. If you use the first option you can still use the bodyMatchers section where you can, using xpath or jspath, to define which parts of the body should be dynamic. It's all matter of preference.