Contract testing is cheaper & more stable alternative of integration tests. Comparing to "setting house on fire to test smoke alarm" (real integration test), it's safe without having to deploy first.
Contract tests application area: where two services talk to each other (across context boundary):
Example: API & web front-end.
Help to avoid "version hell".
Best for microservice.
Should focus on messages (request & response) rather than behavior (not general functional tests).
For testing the contract used for communication
Should be data independent - best when successful verification doesn't depend on specific data in response. NOT for UI behavior & business logic
Should just focus on ensuring request creation & response handling are correct
Ideally should be driven by client's unit tests
Pact is consumer driven - contract as part of consumer tests, so only he part that consumer actually uses get tested, and the rest can still be free to change without breaking tests. It's also "contract by example", uses test cases vs. schema/specification (OAS).
Consumer - receives data (front-end, message end-point)
Provider - provides data (API)
Pact - contract between consumer/provider, is a collection of Interactions
Interaction:
Expected request (consumer -> provider), required for synchronous interactions, optional for asynchronous
Minimal expected response (provider -> consumer)
For interactions that depend on each other, use 'provider states' that describe preconditions on provider to generate expected response.
NOT testing "create user 123 then login"
Write two interactions - 'create user 123' & 'log in user 123' with provider state 'user 123 exists'
Consumer testing:
Pact DSL : expected request and response registered with mock service
Driven by consumer unit test framework, test code fires real request to mock provider provided by Pact framework
Mock provider matches request with registered expected requests, returns expected response
Consumer test code confirms consumer behavior (where response is correct & expected)
After all interactions tested on consumer side, Pact framework generates a Pact File, that can be used to test provider
Provider testing:
Driven by Pact framework
Request sent to provider, response compared with minimal expected response
Provider state: allow setup the data by provider state before interaction is replayed