Contract testing

Also known as: consumer-driven contract testing

On this page 7

Contract testing is a testing technique in programming that verifies whether two communicating components, typically a consumer and a provider of an API or message stream, agree on a shared contract: the exact requests, responses, fields and data types each side expects. Instead of deploying both systems together, each side is tested in isolation against the same contract, which makes the check fast, repeatable and independent of shared environments.

The most common variant is consumer-driven contract testing, in which the consumer records its expectations and the provider proves that it satisfies them. Within the wider practice of testing, contract testing sits between the unit test and the integration test: it is narrower than an end-to-end run, but it catches the interface mismatches that unit tests with mocks cannot see.

How contract testing verifies an interface

Contract testing works by turning an interface agreement into an executable artifact that both sides test against. In the consumer-driven flow, the consumer test suite runs against a mock provider that records every interaction the consumer actually makes. The recorded interactions become a contract file, often called a pact, which is published to a shared store.

The provider then runs a provider verification step: a tool replays each recorded request against the real provider code and compares the actual response with the expected one. If a field is missing, renamed or has the wrong type, verification fails and the provider team learns about the breaking change before deployment. Provider states, such as “order 42 exists”, let the provider set up the data each interaction assumes.

The table below lists the main elements of a typical contract testing workflow and the role each one plays.

ElementOwnerPurpose
Consumer testConsumer teamExercises client code against a mock provider
Contract fileGenerated by consumerRecords expected requests and minimal responses
Contract brokerShared infrastructureStores versions and verification results
Provider verificationProvider teamReplays interactions against the real service
Provider stateProvider teamPrepares test data an interaction depends on
Deployment checkBoth teamsBlocks release when versions are incompatible
Elements of a consumer-driven contract workflow

Consumer-driven and provider-driven contracts

Contracts can originate from either side of the interface, and the choice changes who controls compatibility. In consumer-driven contracts, each consumer states only the fields it really uses, so the provider may change everything else freely. In provider-driven contracts, the provider publishes a specification, for example an OpenAPI document, and consumers check that their usage conforms to it.

A third approach, sometimes called bi-directional contract testing, compares a consumer contract with a provider specification statically, without replaying requests. It is cheaper to adopt but gives weaker guarantees, because a specification can drift from the real implementation.

StyleSource of truthMain strengthMain weakness
Consumer-drivenConsumer expectationsTests only fields in real useNeeds consumer team buy-in
Provider-drivenProvider specificationSimple for public APIsCannot see which fields matter
Bi-directionalBoth, compared staticallyLow adoption effortRelies on accurate specifications
Schema-based messagingShared message schemaFits event streamsChecks shape, not semantics
Contract styles compared

Contract testing also applies to asynchronous messaging. For queues and event streams, the consumer defines the message it can process, and the provider proves that its producer code emits a message with that shape. Schema registries for Avro or Protobuf provide related compatibility checks, although they validate structure rather than consumer-specific expectations.

How contract testing differs from neighboring test types

Contract testing complements rather than replaces other layers of the test pyramid. A unit test with a mock or test stub confirms internal logic but trusts that the mock is accurate; contract testing keeps the mock honest by verifying it against the real provider. An integration test or end-to-end test confirms that deployed systems cooperate, but it is slower, harder to debug and dependent on a shared environment.

Test typeWhat it provesEnvironment neededTypical speed
Unit testLogic inside one componentNoneMilliseconds
Contract testBoth sides agree on the interfaceNone beyond each serviceSeconds
Integration testComponents work togetherReal dependenciesSeconds to minutes
End-to-end testComplete user journeys workFull deployed systemMinutes
Acceptance testBusiness requirements are metUsually stagingMinutes
Contract testing next to related test types

A common misconception treats contract testing as functional testing of the provider. A contract should describe the shape and essential values of an interaction, not business rules such as discount calculations. Encoding business logic in contracts produces brittle tests that fail for reasons unrelated to compatibility.

Adopting contract testing in a delivery pipeline

Contract testing delivers most value in microservice architectures where many independently deployed services talk to each other and teams release on different schedules. The decisive practice is a can-i-deploy check: before a release, the pipeline asks the contract broker whether the version about to be deployed has been verified against the versions currently running in the target environment.

  1. Write consumer tests for one critical interaction and publish the generated contract.
  2. Add provider verification to the provider build, with provider states for required data.
  3. Tag or record which versions run in each environment.
  4. Gate deployments on the compatibility check for both consumer and provider.
  5. Extend coverage gradually to other consumers and message channels.

The following decision table shows when contract testing is a good investment and when another technique fits better.

SituationRecommended choiceReason
Internal services owned by separate teamsConsumer-driven contractsBoth teams can maintain their side
Public API with unknown consumersProvider specification checksConsumers cannot publish contracts
Event-driven system with a schema registryMessage contracts plus schema rulesCovers shape and evolution
Monolith with in-process callsUnit and integration testsNo network interface to protect
Third-party API outside your controlRecorded responses and monitoringThe provider will not run verification
When to choose contract testing

Limitations and common mistakes

Contract testing has clear limits. It does not prove the system works end to end, it does not test performance or security, and it only protects interactions that someone has written a contract for. It also requires organizational discipline, because consumer and provider teams must agree on a broker, versioning rules and a shared release gate.

  • Over-specified contracts: asserting exact values instead of types or patterns makes contracts fail on harmless data changes.
  • Contracts written by the provider for the consumer: this removes the consumer’s real expectations and defeats the purpose.
  • Skipping provider states: verification then depends on whatever data happens to exist.
  • No deployment gate: contracts verified but never consulted at release time give a false sense of safety.
  • Treating contracts as documentation only: unverified contract files drift just like any other document.

Teams that avoid these mistakes typically reduce reliance on slow shared staging environments and detect breaking interface changes in the provider’s own build, often minutes after the change is committed.

In simple terms

Contract testing is like two companies signing a delivery agreement before they ever exchange goods. The buyer writes down exactly what it expects to receive, and the seller checks its own warehouse against that list. Neither side needs the other present to know that the delivery will fit.

In software, one program asks another for data. Contract testing records what the asking program needs and lets the answering program prove it still provides it. The key benefit is catching broken connections early, before anything reaches real users.

A practical example

An online retailer runs a checkout service that calls a separate inventory service through an HTTP API. The checkout team writes consumer tests stating that a request for a product returns sku, available as a boolean and quantity as an integer. These tests generate a contract that is published to a broker.

Months later, the inventory team renames quantity to stockLevel during a refactoring. Their provider verification fails in the build within minutes, and the can-i-deploy check blocks the release. The inventory team adds the new field while keeping the old one until the checkout team migrates. The breaking change never reaches production, and no shared staging environment was needed to find it.