Skip to content

What is contract testing?

Mikhail Bodnarchuk

Definition

Contract testing checks that two services agree on the messages they exchange, without running both at once. The consumer records the requests it sends and the response fields it relies on as a contract, and the provider replays that contract against its real code. A failure names the interaction that broke, before either side deploys.

How does contract testing work?

Two services talk over an API: a consumer (a web shop, a mobile app, another service) and a provider (the API it calls). Each team tests its own side against a stand-in for the other. The open question is whether the stand-in is still accurate. Martin Fowler described the fix in 2011: keep testing against the double, and add contract tests that "check that all the calls against your test doubles return the same results as a call to the external service would" (Contract Test, January 2011, renamed from "Integration Contract Test" in 2018).

Pact, an open-source tool from the Pact Foundation, automates the idea in five steps (How Pact works, Can I Deploy):

  1. The consumer test runs against a Pact mock server. The test declares each request it sends and the parts of the response it uses.
  2. Pact writes the contract. A JSON "pact file" records every interaction from the test, limited to the fields the consumer declared it uses.
  3. The contract is shared. Usually through a Pact Broker, which stores pacts and verification results by version.
  4. The provider verifies it. Pact replays each request against the real provider code, after a provider state handler sets up the data (for example "order 42 exists"), and compares the responses.
  5. The pipeline asks before deploying. The Broker's can-i-deploy check looks up whether this version was verified against the versions already running in the target environment.

Pact calls the result "contract by example": unlike a schema such as an OpenAPI document, which "describes all possible states of a resource", a pact is a set of concrete request and response pairs.

What is the difference between consumer-driven and provider-driven contract testing?

Consumer-driven contract testingProvider contract testing
Who writes the contractEach consumer, from its own testsThe provider, usually as an OpenAPI document
What it provesThe provider still serves what each consumer usesThe provider matches its own documentation
CatchesA renamed or removed field that a consumer readsCode and docs drifting apart
MissesEndpoints no consumer has tested yetConsumers that call the API in the wrong way
Typical toolsPactOpenAPI response validation in the provider's tests

The Pact docs are blunt about the second column: provider contract testing alone "does not provide any test based assurance that the consumers are calling the provider in the correct manner" (Pact introduction, updated August 2026). You can run both: the OpenAPI document for partners and public clients, Pact for the services they own on both sides.

How is contract testing different from integration and end-to-end testing?

Contract testIntegration testEnd-to-end test
Services running at onceOne per side, never bothTwo or moreAll of them
ChecksMessage format and the fields each consumer relies onThat components work togetherA complete user journey
When it failsPoints to the exact interaction and fieldSomewhere between the componentsSomewhere in the journey
Needs a shared environmentNoOftenYes

Contract tests do not check business logic. A provider can return a well-formed order with the wrong total and still pass. That is the job of the provider's own API tests.

Example: a consumer-driven contract with Pact JS

The consumer is a web shop that reads orders from an orders service. Its test runs on Node.js's built-in test runner and declares the response it relies on. The matchers integer() and like() match by type, so the provider can return any integer ID or status string:

// consumer.test.js (web-shop)
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { PactV4, MatchersV3 } from '@pact-foundation/pact'
import { getOrder } from './client.js'

const { like, integer } = MatchersV3
const pact = new PactV4({ consumer: 'web-shop', provider: 'orders-service', dir: './pacts' })

test('web-shop reads an order from orders-service', async () => {
  await pact
    .addInteraction()
    .given('order 42 exists')
    .uponReceiving('a request for order 42')
    .withRequest('GET', '/orders/42', (b) => b.headers({ Accept: 'application/json' }))
    .willRespondWith(200, (b) =>
      b.jsonBody({ id: integer(42), status: like('paid'), totalCents: integer(2400) }))
    .executeTest(async (mock) => {
      const order = await getOrder(mock.url, 42)
      assert.deepEqual(order, { id: 42, status: 'paid', totalCents: 2400 })
    })
})

The provider side replays the pact file against the real HTTP server:

// provider.test.js (orders-service)
import { test } from 'node:test'
import { Verifier } from '@pact-foundation/pact'
import { server, seed } from './provider.js'

test('orders-service honors the web-shop contract', async () => {
  await new Promise((ok) => server.listen(3125, ok))
  try {
    await new Verifier({
      provider: 'orders-service',
      providerBaseUrl: 'http://localhost:3125',
      pactUrls: ['./pacts/web-shop-orders-service.json'],
      stateHandlers: { 'order 42 exists': async () => seed({ id: 42, status: 'paid', total: 2400 }) },
    }).verifyProvider()
  } finally {
    server.close()
  }
})

Tested on 2026-11-19 with @pact-foundation/pact 17.1.4 (Pact Specification 4.0 in the generated file) and Node.js 22.23.5. The consumer test passed and wrote pacts/web-shop-orders-service.json. The provider verification passed too (excerpt, log lines removed):

Verifying a pact between web-shop and orders-service
  a request for order 42 (0s loading, 31ms verification)
     Given order 42 exists
    returns a response which
      has status code 200 (OK)
      includes headers
        "Content-Type" with value "application/json" (OK)
      has a matching body (OK)

Then the provider team "tidied up" the response and renamed totalCents to amountCents. Their own unit tests would pass. The contract did not (excerpt):

      has a matching body (FAILED)
Failures:
1) Verifying a pact between web-shop and orders-service Given order 42 exists - a request for order 42
    1.1) has a matching body
           $ -> Actual map is missing the following keys: totalCents
There were 1 pact failures

The test exited with code 1 on the provider's side, before any deploy, and named the consumer and the field.

When is contract testing worth it, and when is it not?

Pact's own guidance (page last updated April 2022) says it fits best when you control both the consumer and the provider, both are under active development, and a provider has few enough consumers that its team can work with each one (When to use Pact).

It lists cases where Pact is the wrong tool:

  • public APIs, where consumers "cannot be individually identified";
  • performance and load testing;
  • functional testing of the provider;
  • pass-through APIs that forward a request without validating it.

For a public API, publish an OpenAPI document, validate the provider against it and version breaking changes.

What should you check before relying on contract tests?

  1. Verification runs in the provider's CI on every change, not only when the consumer publishes a new pact.
  2. Results are published from CI only. For publishVerificationResult, the Pact JS provider docs note: "you should only enable this during CI builds".
  3. Deployments are recorded. can-i-deploy can only answer if the Broker knows which versions run in each environment (Can I Deploy).
  4. Provider states set up real data paths, not a stub that bypasses the code under test.
  5. Usage tracking is on unless you turn it off. Without PACT_DO_NOT_TRACK=true, our run printed that Pact tracks usage events anonymously; with the variable set, the notice was gone. Decide which setting your CI should use.

Our API and integration team designs APIs contract-first with OpenAPI or AsyncAPI and ships each integration with contract and API tests, so a change on either side fails in CI first. If AI agents will call your services too, our post on making APIs ready for AI agents covers contracts, auth and rate limits.

Sources

  1. Contract Test, martinfowler.com (Martin Fowler), 2011-01-12
  2. Introduction, Pact docs (Pact Foundation), 2026-08-25
  3. How Pact works, Pact docs (Pact Foundation), 2024-12-23
  4. When to use Pact, Pact docs (Pact Foundation), 2022-04-13
  5. Can I Deploy, Pact Broker docs (Pact Foundation), 2022-10-05
  6. Pact tooling, Pact docs (Pact Foundation), 2026-01-08
  7. Provider verification (pact-js docs/provider.md), Pact Foundation on GitHub, 2026-11
  8. @pact-foundation/pact 17.1.4, npm, 2026-09-07

Frequently asked questions

Is contract testing the same as API testing?

No. It is a narrow kind of API check: it verifies only the message format and fields that consumers rely on. Functional API tests still need to check that the provider computes the right answers and enforces access rules.

What is Pact contract testing?

Pact is an open-source, code-first tool for consumer-driven contract tests over HTTP and messaging. Consumer tests generate a pact file and the provider verifies it in its own build; Pact has implementations in more than 10 languages, including JavaScript, Java, .NET, Go and Python.

Can contract tests replace end-to-end tests?

They replace many of them in a microservice system, because each service connection can be checked without deploying everything together. Keep a few end-to-end journeys for the paths that matter most, since contracts do not prove the business flow works.

Does contract testing work for event-driven systems?

Yes. Pact supports message pacts, where the contract is the message a producer puts on a queue or topic and the consumer's handler is tested against it.

Mikhail BodnarchukMikhail BodnarchukFounder of Codeception and CodeceptJSBoth are open-source testing frameworks: Codeception for PHP, CodeceptJS for JavaScript.LinkedInGitHub

Building with AI agents? Talk to an engineer.