Contract testing

A contract is an agreement that explains the way in which two parties deal. In the same way, a contract in the context of services is an agreed format in which a service should be called. Alternatively, in the microservice context, we can say that it is an agreement between a consumer and an API provider that describes the exact manner of communication and the format of the expected input and output. Contract testing is different as compared to integration testing. Let's understand this with an example. Suppose we have a loan servicing application. Before sanctioning a loan to the customer, our application needs to deal with third-party service to know the existing loan amount for that customer, which they might have taken from another bank or a lending company. What happens if, for some reason, someone changes the contract on the third-party service side? Our application integration test works perfectly fine, as we have mocked the external service, but in the production environment, it will fail. This is where contract testing comes into the picture.

All services should be called one by one, independently, and their responses should be matched with the contracts. It should match only input and output contracts without worrying about internal code. For any dependency service, they should be mocked like other testing techniques. For contract testing, one has to design the test case for the API provider, run test cases against it, and store the result somewhere. Now, the related test cases should be run on the client/consumer side and then the input given to the provider service and the output coming from the consumer service should match. Alternatively, it can be done in reverse; first, the test case can be run on the client side and its output can be saved, and then this output is given as an input to the provider side. Then, in the same way, match the expected result and the actual result. This makes sure that the contract has not been broken.

Keeping contract testing in mind at the time of development is really helpful in developing the interface, request parameters, and response parameters in a more accurate way. This way, the service developed will be very robust and will always give the expected result to consumers. For example, if we are giving APIs to other services, then the developer should think about it, as it should be extendible in the future by adding new parameters or changing the functionality, which should not break the contract between the service (until some major changes are going to take place in all the services). Contract testing automatically assures that, even after such changes, the contract is not broken. There are some tools to help us out with this, namely, Pact tool and Spring Cloud Contract. Both are open source tools and are available on GitHub.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset