What is contract testing, and why is it useful for microservices?
In one line: Contract testing checks that a service (the provider) still returns what its consumers expect — the "contract" between them — without having to run all services together in a big end-to-end test.
The problem: with 30 microservices, the orders team changes a field name in its API from total to totalAmount. Their own tests pass. But the payments service, which reads total, breaks in production. Full end-to-end tests could catch it, but they're slow and fragile.
How consumer-driven contract testing works (for example with Pact):
- The consumer (payments) writes a test describing what it needs: "when I call
GET /orders/123, I expect JSON withidandtotal". - Running this test produces a contract file (a pact) and publishes it to a broker.
- The provider (orders) runs a verification step in its own pipeline: it replays the contract against its real API.
- If orders removes or renames
total, its own pipeline fails before deploying — the team learns about the break immediately. - "Can I deploy?" checks confirm that the versions in each environment are compatible.
Benefits:
- Catches breaking API changes early, in the provider's CI.
- Much faster and more reliable than full E2E tests across many services.
- Teams can deploy services independently with confidence.
- Contracts document how services actually use each other.
Tools: Pact (most popular), Spring Cloud Contract, and schema-based checks (OpenAPI diff, protobuf/Avro schema compatibility checks in a schema registry).
Example: the orders team tries to rename a field. Pact verification fails in their PR with "payments expects total". They add totalAmount while keeping total for now, and remove it later once payments has been updated.
Tip for interviews: link contract testing to independent deployability — the core promise of microservices.