Why and what is contract testing?
The distributed nature of microservices, combined with the sheer number that live within an application, make it much harder for developers to perform the integration tests that were a straightforward, routine part of monolithic app development.
Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a "contract".
Consumer-driven contract testing is a type of contract testing that ensures that a provider is compatible with the expectations that the consumer has of it. This involves checking that the provider accepts the expected requests, and that it returns the expected responses.
Consumer contract testing provides the following benefits:
- Contract tests provide a mechanism to explicitly verify that a provider microservice meets a consumer’s contract/needs.
- These HTTP requests and responses are used in the mock HTTP server to mock the service provider. The interactions are then used to generate the contract between a service consumer and a service provider.
- If the provider returns something unexpected, Pact marks the interaction as a failure, and the contract test fails.
- A consumer’s contract test is made available to the provider to verify. By testing each side of an integration point using a simulated version of the other microservice, we get two sets of tests, one to define the interaction required and the other (playback) to verify the provider is meeting the needs defined in the consumer contract.
Contract testing for microservices is not without challenges.
The main challenge is that you'll need to run many individual tests to evaluate all microservices within your application. In this sense, contract testing is trickier to orchestrate than end-to-end integration testing. Integration testing only requires one testing environment and one set of tests. Contract testing requires teams to run a long series of tests, each for a different pair of microservices.
Another major limitation of contract testing revolves around the use of mocks. Although a mock is a reliable way of mimicking microservice behavior without running a microservice, there's no guarantee that the actual microservice will behave in the same way when in production. Due to the nature of the instances spun up, integration testing isn't subject to this same limitation.
Finally, teams must be sure to keep contracts up to date. The contract testing process needs to loop in each development team and its members so that they can help to define new contract requirements whenever they make changes to a microservice's functionality or behavior. Otherwise, tests will become based on contracts that no longer accurately reflect the desired behavior of a microservice.
Comments