Skip to content

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:

  1. Consumer writes tests describing what it expects from the provider
  2. These expectations are extracted as a "contract" (JSON file)
  3. 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:

  1. Fast — no integration test setup
  2. Independent deployment — consumer and provider can deploy separately
  3. Early detection — contract mismatch caught before deployment
  4. Documentation — the contract IS the API documentation

Tools: Pact (multi-language), Spring Cloud Contract (Java).

Example

javascript
// 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

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary