Contract Tests: Testing API Boundaries
What you'll learn: You'll learn how contract tests ensure that different services or modules communicate correctly by verifying they honor their agreed-upon API specifications.
The Core Idea
Imagine two teams building separate services: a payment service that provides an API, and a shopping cart service that consumes it. Contract testing ensures both sides honor their agreement about how the API works—the "contract."
Unlike integration tests that actually connect the real services, contract tests verify each side independently against a shared specification. The provider tests that it returns responses matching the contract, while the consumer tests that it sends requests and handles responses correctly according to the contract.
Why Contract Tests Matter
When services change independently, subtle mismatches can break integrations. Did the payment API rename a field from customer_id to customerId? Does it now return 201 instead of 200 on success? Contract tests catch these breaks before deployment.
They live between unit and integration tests in your testing pyramid—broader than isolated unit tests but faster and more focused than full end-to-end tests.
The Contract as Truth
The contract document describes:
- Expected request formats and parameters
- Response structures and status codes
- Error conditions and messages
- Data types and validation rules
Both teams test against this shared contract file. If the payment service passes its provider tests and the cart service passes its consumer tests, they should integrate successfully.
Key Takeaway: Contract tests verify that APIs meet their documented specifications on both sides of the boundary, catching integration issues early without requiring both services to run together during testing.