Writen by Rodrigo Tejada, in 05/27/2022

5 minutes of reading

Contract Tests

Thats why something called Contract Test is needed. Its a methodology for ensuring that your contract stays compatible and will fail when any breaking change is introduced.

Share:

Then we will need to add SpringCloudContract to our classpath to be able to declare our contract test in groovy:

And we’ll need to configure spring-cloud-contract-maven-plugin with the name of our base test class:

Then the contract can be written in a declarative form and a test will be generated from this file:

In order to mock the service implementation and only keep the contract beeing tested we must written a default class that will be extended on the generated test:

The generated test will look like this:

This way, on your build pipeline not only the unit tests will run but also these generated contract tests always validating the introduced code. There are a lot of other functionalities on Spring Cloud Contract that can help your development, for example it will generate a “stubbed jar” using wiremock, that will respond accordingly to the groovy declarative tests, in a way that consumers can import this jar an use it for testing their calls to our API without the real call. So on the consumer side a test can be written like this:

Spring Cloud Contract is a great tool to help our contract tests but it is not the only tool available, when leaving the spring framework and diving into java servlet for example, jersey can be used to solve this problems and other tooling can be used to do the same thing, but the most important is that by implementing contract test we can guarantee that our communication with several clients will remain compatible no matter what change is done on our implementation.

GITHUB: Rodrigo Tejada

Share it: