Contract Testing
In one line
Contract testing ensures API providers and consumers agree on the interface — without needing full integration tests.
In simple words
Contract testing is for microservices and APIs. Instead of running full integration tests (which are slow and fragile), each side tests against a shared "contract" that defines the expected request/response format.
How it works:
- Consumer writes tests describing what it expects from the provider
- These expectations are extracted as a "contract" (JSON file)
- Provider verifies it can satisfy the contract
This decouples consumer and provider testing:
- Consumer tests run against a mock that follows the contract
- Provider tests verify the contract is met
- No need to run both services together
Benefits:
- Fast — no integration test setup
- Independent deployment — consumer and provider can deploy separately
- Early detection — contract mismatch caught before deployment
- Documentation — the contract IS the API documentation
Tools: Pact (multi-language), Spring Cloud Contract (Java).
Example
// Consumer test (JavaScript with Pact)
const pact = new PactProvider({
consumer: 'OrderService',
provider: 'UserService',
});
pact
.given('user 42 exists')
.uponReceiving('a request for user 42')
.withRequest({ method: 'GET', path: '/users/42' })
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: { id: 42, name: 'Ada' },
});
// Provider verification (separate test)
pact.verifyProvider({
providerBaseUrl: 'http://localhost:8080',
pactUrls: ['./pacts/userservice-orderservice.json'],
});
// If provider changes its API, contract verification fails.Consumer defines expectations → contract generated → provider verifies it can satisfy the contract. No integration test needed. Pact is the most popular tool.
Common confusions
Confused with: integration testing
The difference: Integration testing runs both services together and tests their interaction end-to-end — slow, fragile, requires both services running. Contract testing tests each side independently against a shared contract — fast, decoupled, catches API mismatches early. Contract testing replaces many integration tests.
Related terms
Related Resources
Related Lessons
- API Testing
Contract testing.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.