Contract testing
Consumer-driven contracts with Pact: consumer expectations verified against the real provider in CI. Replaces a whole class of slow integration environments.
The mental model
Contract testing replaces a slow, flaky integration environment with a signed agreement checked at both ends independently. The consumer writes down exactly what it sends and expects back; the provider proves it can honour that agreement — and neither has to be running at the same time.
The analogy that sticks: a restaurant and its suppliers. Integration testing is inviting every supplier into the kitchen at once during dinner service to see if the meal comes out right — expensive, chaotic, and if one supplier is late the whole test stalls. A contract is instead a written order sheet: "I need 5kg of tomatoes, graded A, delivered by 9am." The kitchen (consumer) records the exact order it places; the supplier (provider) independently verifies "yes, I can fulfil an order shaped like this." You test the interface between them without ever assembling the whole restaurant.
The one idea that explains why it works: the contract is generated from the consumer's real expectations, not written by hand. When the consumer's tests run against a mock, Pact records every request/response pair that mock actually served. That recording is the contract. So the contract can never drift from what the consumer really needs — and the provider verifies against that recording, catching a breaking change the moment the provider's real response stops matching. This is the gap that unit tests structurally cannot close: the provider's unit tests all pass because its own assumptions are self-consistent; only the consumer's contract knows the field was renamed.
- Deep dive
- Internal architecture
- Real-world use cases
- Best practices
- Common mistakes
- Performance
- Security
- Production troubleshooting
- Advantages & disadvantages
- Alternatives
- Interview expectations
- Interview questions
- Facts to remember
- Cheat sheet
- Quick revision