Testing Your MicroService using Contract testing Part-1.
When A project is small and there are only 2–3 microservices, it is easy to manage. we know only these 2–3 microserivces will be using each other. so if We made changes in any microservices input or output structure , it is easy to communicate and change. But think about A large application where there are 100's of microservices. and Any microservice can use each other.
Example Below microserives mesh of amazon and netflix.
So Question is , How you are going to make sure your changes does not break other microserivices ? Or How other microserivces make sure Changes in other microservices is not breaking in their services.
Answer to these questions is Contract testing.
Contract testing is a way to ensure that services (such as an API provider and a client) can communicate with each other. Without contract testing, the only way to know that services can communicate is by using expensive and brittle integration tests.
On a broad level, contract testing can be thought of as testing the communication layer between services. Contract testing tests that any pair of dependent services can properly send and decode messages between each other, but doesn’t test the services’ internal logic. As such, contract testing exists somewhere on the boundary between integration testing and end-to-end testing.
And to do contract testing we have open source know as pact. it can be found at pact.io
here are two main types of actors in contract testing, Providers and Consumers.
Consumer: A client that wants to receive some data (for example, a web front end, or a message receiving endpoint).
Provider: A service or server that provides the data (for example, an API on a server that provides the data the client needs, or the service that sends messages).
A contract between a consumer and provider is called a pact. Each pact is a collection of interactions. Each interaction describes:
- An expected request — describing what the consumer is expected to send to the provider (this is always present for synchronous interactions like HTTP requests, but not required for asynchronous interactions like message queues)
- a minimal expected response — describing the parts of the response the consumer wants the provider to return.
This contract or pact make sure communication between services happens as expected.