How-To Guide

How to Do Contract Testing Between Services

Verify that a service and its consumers agree on an API by testing each side against a shared contract instead of a live peer.

On this page

  1. Introduction
  2. The Problem with End-to-End Only
  3. Consumer-Driven Contracts
  4. Provider Verification
  5. The Broker and Version Selection
  6. What Contracts Should and Should Not Cover
  7. Keeping Contracts from Rotting
  8. Conclusion

Introduction

Integration tests that start both a provider and a consumer are slow, flaky and hard to run in isolation. Worse, they pass in the test environment while the two sides drift apart in production, because the test never pinned what the consumer actually needs. Contract testing solves this by having the consumer declare what it expects and the provider verify that it honours every declared expectation. The two never need to run together: each tests against the contract, and the contract is the shared truth. This makes the tests fast enough to run on every commit and precise enough to point at the side that broke. This article covers consumer-driven contracts, provider verification, and how to keep contracts from becoming a second source of truth that rots.

The Problem with End-to-End Only

An end-to-end test for two services requires both to be running, their databases to be seeded, and their versions to be compatible. When it fails you do not immediately know which side broke. And when it passes, it only passed for the specific data and versions you happened to deploy; a consumer using a different field or a different edge case is untested. The test gives confidence about one path and silence about the rest.

Contract testing splits the problem. The consumer writes a test that mocks the provider and records the interactions it relies on. The provider replays those interactions against its real implementation and verifies it honours them. No environment is shared, each side runs fast, and a break on either side fails on that side.

Consumer-Driven Contracts

In a consumer-driven contract, the consumer is the source of the expectations. This matters because the provider does not know which fields consumers actually use; a field the provider thinks is internal may be load-bearing for a consumer. By recording the interactions, the consumer turns its implicit dependency into an explicit, checkable claim.

// consumer side: define the interaction the consumer relies on
const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like, integer } = MatchersV3;

const provider = new PactV3({
  consumer: 'orders-web',
  provider: 'users-api',
  dir: './pacts',
});

it('gets a user by id', async () => {
  provider
    .given('user 42 exists')
    .uponReceiving('a request for user 42')
    .withRequest({ method: 'GET', path: '/users/42' })
    .willRespondWith({
      status: 200,
      body: { id: integer(42), email: like('[email protected]'), active: like(true) },
    });

  await provider.executeTest(async (mock) => {
    const user = await getUser(mock.url, 42);
    expect(user.id).toBe(42);
  });
});

Provider Verification

The provider fetches the recorded contracts and replays each interaction against its real server. In a stateful system, the provider must set up the “given” state, such as ensuring user 42 exists, then assert the response matches. A failure names the consumer and the interaction, so the provider knows exactly which expectation it broke. Run provider verification in the provider’s CI so a breaking change fails there, before it reaches consumers.

// provider side: verify every recorded consumer interaction
const { Verifier } = require('@pact-foundation/pact');
const { app, seedUser, resetDb } = require('./server');

it('honours all consumer contracts', async () => {
  const verifier = new Verifier({
    providerBaseUrl: 'http://localhost:8080',
    pactUrls: ['./pacts/orders-web-users-api.json'],
    stateHandlers: {
      'user 42 exists': async () => { await seedUser({ id: 42, email: '[email protected]', active: true }); },
      'no users exist': async () => { await resetDb(); },
    },
  });
  await new Promise((resolve) => app.listen(8080, resolve));
  const output = await verifier.verifyProvider();
  expect(output).toBeTruthy();
});

The Broker and Version Selection

A broker stores contracts and links them to consumer and provider versions. When a consumer publishes a new contract, the provider verifies against it before a webhook tells the consumer CI that it is safe to deploy. The broker can also answer which consumer versions are compatible with a candidate provider version, which is what lets you deploy in any order without a coordinated release.

Use the “can I deploy” query rather than manual coordination: before deploying a provider, ask the broker whether all consumers that are deployed and still active have contracts the provider satisfies. That is the check that catches a breaking change before it reaches reality, and it is why contracts must be published continuously, not only at release.

What Contracts Should and Should Not Cover

Cover the shape and semantics of the interactions you depend on: paths, methods, status codes, required fields, types and edge cases such as 404. Do not try to reproduce an entire integration test through contracts; they express expectations, not workflows. Keep each interaction small and named by the scenario, so a failure points at one expectation.

Include the error and boundary paths, because those are where drift hurts most. A provider that changes the error body shape while keeping the status code the same breaks consumers that parse the body. A consumer contract that declares the error shape turns that into a verification failure instead of a production bug.

Keeping Contracts from Rotting

A contract that nobody verifies is worse than none, because it claims a guarantee it does not provide. Make provider verification a required CI check and a release gate, and make consumer contract publication part of the consumer’s pipeline. Track which interactions are stale, meaning no active consumer relies on them, and delete them so the contract set stays small and meaningful.

Avoid versioning the contract as a hand-maintained document; generate it from the consumer test so it cannot drift from what the code does. Treat the contract like a generated artifact: the code is the truth and the contract is its output, not the reverse.

Conclusion

Contract testing removes the shared environment from the two-service test: the consumer records what it expects, the provider verifies it honours every recorded expectation, and a broker coordinates versions so either side can deploy independently. Cover the shapes and edge cases you depend on, verify in both pipelines, and query the broker before deploying. Delete stale interactions and generate contracts from tests. The result is fast, isolated tests that catch a breaking change on the side that introduced it.

Sources: Pact documentation, Consumer-driven contracts, Pact broker.

FAQ

Does contract testing replace integration tests?
No. Contracts verify that two sides agree on the API shape and semantics; they do not exercise the real dependencies of the provider. Keep a small number of integration tests for the wiring and use contracts to catch interface drift cheaply and early.
Who should write the contract, the consumer or the provider?
The consumer, because only the consumer knows which fields and behaviours it actually relies on. The provider then verifies it satisfies every recorded expectation, which turns the consumer dependency from implicit to explicit.

Related Examples