PRACTITIONERCHAPTER 08

API, contract and integration testing

Most failures between services are disagreements about a shape or a meaning. Contract tests catch the shape, integration tests catch the meaning, and idempotency tests catch the money

45 MINQA AND QUALITY ENGINEERINGUPDATED 2026-11-05
PREDICT

Your checkout service stubs its external payment provider in every test, and the stubs were written from the provider's docs a year ago. All tests are green. In production, refunds start failing because the provider now returns `amount` as a string. Which test would most cheaply have caught this?

An API is a promise between two teams that rarely sit together. The provider promises a shape (paths, fields, types, status codes) and a meaning (what a 201 implies, whether a retry is safe, what happens to money when a call times out). Consumers write code against that promise, and the code keeps working only while both sides remember it the same way.

As a QA engineer or SDET who owns a team’s test strategy, you own the tests that check the promise. This chapter covers the levels of API testing and what each catches, consumer-driven contracts with Pact, how to test against third parties you do not control, the idempotency and retry tests that matter most in payments and messaging, and the shape of the work week to week. It assumes you have read the idempotency lesson; it does not re-explain the mechanism, only how to test it. API versioning and deprecation policy belongs to the product side and is covered in platform and technical PM; this chapter tests whatever policy that sets.

The levels, and what each one catches

Teams argue about the testing pyramid, covered in the testing philosophies chapter. For APIs the useful question is narrower: for each kind of bug, which test is the cheapest one that can see it?

Level What runs for real What is faked Catches Misses
Unit One function or class Everything else Logic errors, edge cases in parsing Anything about the wire
Component (service in isolation) One service over HTTP, its own database Other services, via stubs such as WireMock Routing, serialisation, error mapping, your own idempotency Whether the stubs are true
Contract Consumer against a mock; provider against recorded expectations The counterpart, in each half Shape drift: renamed fields, changed types, removed endpoints, status codes Behaviour, timing, data flows across more than two services
Integration Two or more real services, real databases, often in containers Third parties, usually Meaning: units, states, ordering, transactions, retries Third-party behaviour, production scale
Sandbox Your code against a provider’s test environment Real money and real networks Drift in a third party’s API, auth and signing Production edge cases the sandbox does not simulate
End-to-end Everything, in a shared environment Little Wiring and configuration Root cause; it is slow and flaky, so it fails for reasons unrelated to your change

Two things follow. First, the end-to-end suite is the most expensive place to catch a renamed field, and the most common place teams try. Contract tests move that check to the pipeline of the team that made the change, minutes after they made it. Second, contract tests do not replace integration tests. The checkout story in the opening had both kinds of bug: the pounds-versus-pence change kept the field name and it stayed a number, so a contract with a like() matcher passes; an integer() matcher catches it only when the amount has pence (49.99 is not an integer, but 50 is); only a test that runs both services and compares the ledger can see that the meaning changed. The double charge was a behaviour bug that only an idempotency test can see.

Contract tests, two meanings

The phrase “contract test” means two different things, and mixing them up causes most of the confusion.

Fowler’s contract test (2011, in the reading) is a test of your test doubles. You stub a remote service in your fast tests. Separately, on a schedule, you run a small suite against the real service that checks the stub’s assumptions still hold. When it fails, your stubs are wrong and you go and talk to the provider. This is the only kind you can run against a service owned by another company.

Consumer-driven contracts (Ian Robinson, 2006, also in the reading) invert the ownership. Each consumer writes down the requests it sends and the parts of the responses it reads. The provider runs all of its consumers’ expectations against its own code in its own pipeline, and a change that breaks a consumer fails the provider’s build before it merges. The provider learns which fields are used, and by whom, which is information no OpenAPI spec gives you.

Pact is the most widely used tool for the second kind. The flow:

  1. The consumer test declares interactions against a mock provider that Pact runs locally. The test exercises your real client code. If the client sends what the interaction declares and handles the response, the test passes and Pact writes a pact file, a JSON document of the interactions.
  2. The pact is published to a Pact Broker (self-hosted or the hosted PactFlow), tagged with the consumer’s version, usually the git commit.
  3. The provider’s pipeline fetches the pacts for its consumers, sets up each provider state, replays each request against the running provider, and checks the response contains at least what the consumer expects. Results go back to the broker.
  4. Before either side deploys, can-i-deploy asks the broker whether this version has a successful verification against the versions of its counterparts recorded in the target environment. After deploying, record-deployment tells the broker what is now there.

Here is a consumer interaction in Pact JS. The consumer is Saltmarsh’s hosted checkout; the provider is Saltmarsh’s own payments API. Both sides belong to one company, which is what lets the provider run the verification.

import { PactV3, MatchersV3 } from '@pact-foundation/pact';
const { like, integer, regex } = MatchersV3;

const provider = new PactV3({ consumer: 'saltmarsh-checkout', provider: 'saltmarsh-payments' });

it('creates a payment intent for a monthly invoice', () => {
  provider
    .given('merchant m_123 exists and accepts GBP')
    .uponReceiving('a request to create a payment intent')
    .withRequest({
      method: 'POST',
      path: '/v1/payment_intents',
      headers: { 'Content-Type': 'application/json', 'Idempotency-Key': like('inv_2026_10_m_123') },
      body: { amount_minor: 4999, currency: 'GBP', merchant_id: 'm_123' },
    })
    .willRespondWith({
      status: 201,
      body: {
        id: like('pi_8f2k'),
        status: regex('requires_capture|succeeded', 'requires_capture'),
        amount_minor: integer(4999),
      },
    });

  return provider.executeTest(async (mock) => {
    const client = new SaltmarshClient(mock.url);
    const intent = await client.createIntent({ invoiceId: 'inv_2026_10_m_123', amountMinor: 4999, merchantId: 'm_123' });
    expect(intent.amountMinor).toBe(4999);
  });
});

Three habits show in that snippet. The response uses matchers (like, integer, regex) rather than exact values, so the provider can return any id and still pass; the contract is about types and shapes, not data. The response lists only the fields billing reads: Saltmarsh returns twenty more, and leaving them out is what tells Saltmarsh it may change them. And the precondition is a provider state, a name the provider maps to setup code, so each interaction runs on its own with no dependence on the one before.

Where practitioners disagree

Consumer-driven or provider-driven. Pact puts the consumer in charge, which works when consumers are internal teams who will write tests. A public API with thousands of unknown consumers cannot collect their pacts; there the provider publishes an OpenAPI document and tests that the implementation conforms to it. PactFlow’s bi-directional contract testing sits between the two: consumers publish pacts, the provider publishes its OpenAPI spec, and the broker checks the pacts against the spec without the provider replaying them. It is cheaper to adopt and weaker, because a spec can claim things the code does not do.

Pact or schema tests. A JSON Schema check on responses is easy and catches type drift. It does not tell the provider who depends on what, and it does not fail the provider’s build; it fails yours, later. The Pact docs make this argument at length.

How much to put in a pact. The common failure is a consumer that asserts every field and exact values, which turns the pact into a brittle snapshot that fails on harmless changes. The rule the Pact docs give is Postel’s: be strict in what you send, loose in what you accept. Assert what your code reads, with type matchers. Business rules (“a refund larger than the capture is rejected”) belong in the provider’s own functional tests, not in the contract.

Integration tests: where meaning lives

Contract tests check that both sides agree on a shape. Integration tests check that the shape means the same thing at both ends and that the system behaves when real components fail in real ways. For a service that moves money or messages, the integration suite earns its cost in four places.

Units and semantics. Amounts in minor units or major, timestamps in UTC or local, a status that means “authorised” to one team and “paid” to another. Run the producer and the consumer together, with real databases in containers (Testcontainers is the common tool), and assert on the end state: the ledger row, the balance, the delivered message. The payment ledger lesson shows why the end state is the thing to check, and testing money and regulated systems turns that into reconciliation tests.

Timeouts and ambiguous outcomes. When a call times out, the client does not know whether it happened. Test it: make the provider stub accept the request, commit, then delay the response past the client’s timeout. The client should retry with the same key and end with one effect. The timeouts lesson and retries, backoff and jitter cover the mechanism; your job is to make the failure happen on purpose in a test.

Webhooks. Providers deliver events at least once, sometimes out of order, sometimes days late after an outage, and sign them. A webhook receiver needs tests for a duplicate delivery (processed once), an older event arriving after a newer one (state does not go backwards), an invalid signature (rejected with no side effect), and a slow handler (the provider retries, so the receiver must acknowledge fast and process later). Replaying a recorded delivery is the cheapest way to write each of these.

Error contracts. Consumers depend on error responses as much as successes: the 402 that means card declined, the 409 that means a request is in flight, the error code a mobile client turns into a message. Put the important errors in the pact as interactions with their own provider states, and test that your client handles each one.

The idempotency tests

Payments and messaging both live on retries, and the bug that costs money is the retry that acts twice. Every endpoint that creates something needs three tests, and the second is the one most suites lack.

test('same key, retried and concurrent, charges once; different body is rejected', async () => {
  const key = randomUUID();
  const body = { amount_minor: 4999, currency: 'GBP', merchant_id: 'm_123' };
  const post = (b) => api.post('/v1/payment_intents').set('Idempotency-Key', key).send(b);

  // Concurrent duplicates: one wins, the other sees the stored result or 409 in flight.
  const [a, b] = await Promise.all([post(body), post(body)]);
  const statuses = [a.status, b.status];
  expect(statuses).toContain(201);
  statuses.forEach((s) => expect([201, 409]).toContain(s));

  // Sequential retry after both settle: same id, no new charge.
  const retry = await post(body);
  expect(retry.status).toBe(201);
  expect(retry.body.id).toBe(a.status === 201 ? a.body.id : b.body.id);

  // Same key, different amount: a client error, not the first result.
  const changed = await post({ ...body, amount_minor: 9999 });
  expect(changed.status).toBeGreaterThanOrEqual(400);
  expect(changed.status).toBeLessThan(500);

  expect(acquirerStub.authorisations()).toHaveLength(1);
});

The final assertion is the one that matters: count the side effects at the boundary, here the acquirer stub’s received authorisations, not the API responses. Run the concurrent half many times in CI, because a race that loses one time in fifty passes most runs. The exact status for a reused key with a different body varies by API (Brandur Leach’s write-up of Stripe-style keys, in the reading, covers the design); what must not vary is that it is an error and nothing is charged.

Testing against third parties

Your payment provider, your SMS gateway and your identity provider will not run your pacts. You have three tools, and most teams need all three.

Stubs built from recordings. WireMock or a similar tool, loaded with real responses captured from the sandbox, including the failures. They run in every pipeline and let you produce faults the sandbox cannot: a 30-second delay, a connection reset, a malformed body.

A scheduled sandbox suite. Twenty to fifty calls, run nightly or hourly, that exercise the endpoints you use and compare the responses with your stubs. This is Fowler’s contract test. When it fails, update the stubs, then find out whether your code survives the change. Sandboxes have their own limits: Stripe’s testing docs, for example, say test mode has stricter rate limits and must not be used for load testing, so keep the suite small.

A release smoke test. A handful of calls against the sandbox from the release pipeline, with the real credentials and signing configuration for that environment. It catches the class of bug where every test passed and the production secret was wrong.

Watch the provider’s changelog as well. Most payment providers announce changes weeks ahead, and reading that page monthly is cheaper than the incident.

Postman, Newman and the CLI

Postman is where many API tests start: a collection of requests with test scripts, shared across a team, used for exploration and for reproducing bugs. Newman runs collections from the command line so they can gate a pipeline. Postman’s own documentation now says Newman no longer receives updates and recommends the Postman CLI in its place, so new pipelines should start there.

Collections are good at smoke tests, exploratory work and documentation by example. They are weak at the things in this chapter: they do not create contracts a provider verifies, they share state between requests by default, and assertions written in a GUI tend not to get code review. Use them for what they are good at, and keep contract and idempotency tests in code beside the service.

Day to day

Every pull request. Contract changes show up as a diff in the consumer’s test file or as a provider verification failure. You review both. A consumer pact that asserts exact values or every field gets a comment; a provider change that fails a consumer’s verification gets a conversation with that consumer’s team before anyone edits the pact.

Daily, ten minutes. Check the broker for failed verifications and the overnight sandbox suite for drift. A sandbox failure is either the provider changing something (update stubs, raise with the integration owner) or the sandbox being down (note it, do not chase it).

Weekly. In the team’s planning, look for stories that add or change an endpoint and add the contract and idempotency cases to their acceptance criteria. Pair for an hour with a developer writing their first pact; the second one they write alone.

At API design reviews, which run whenever a team proposes a new endpoint, ask the testing questions early: what is the idempotency key, what happens on timeout, which errors will consumers branch on, which provider states will be needed. The answers shape the API and they are much cheaper to change before it ships.

Monthly. Read the changelogs of your third-party providers. Prune provider states nobody uses. Look at the verification times; a provider build that takes twenty minutes to verify pacts will be bypassed.

At release. can-i-deploy runs in the pipeline as a gate. You own what happens when it says no, which is usually a consumer that has not deployed the version the provider expects. That conversation, between two teams who both want to ship, is a large part of the job at this level.

BY ORG SIZE
STARTUPunder 30 people

One service, a mobile app and a payment provider. Pact is overhead you do not need yet: the team that changes the API also ships the app, often in the same week. What you need is the idempotency test on every endpoint that creates money or messages, a webhook replay test, stubs recorded from the provider’s sandbox, and a nightly run against the sandbox. A developer usually owns all of it. If there is a mobile app on release cycles you cannot force, that is the first place a consumer contract pays.

SCALE-UP30 to 300

Ten to forty services, owned by different teams, and the end-to-end suite has become slow and distrusted. This is where consumer-driven contracts earn their cost, and where a QA engineer or SDET usually introduces them: a broker, two teams piloting, then can-i-deploy as a gate. The hard part is social. Provider teams have to agree that a consumer’s pact can block their build. Start with one provider and its two heaviest consumers, show a caught break, then expand.

ENTERPRISE300 and up

Hundreds of services, public APIs with external consumers, and several third-party providers per domain. A platform team runs the broker; contract tests are a pipeline standard rather than a team choice. Public APIs use provider-driven OpenAPI tests, often bi-directional, because external consumers will not write pacts. Shared sandboxes hit rate limits and get contended between teams, so access is scheduled. Your work moves to standards, reviewing contract coverage across teams, and arguing for retiring the end-to-end environment nobody trusts.

ARTEFACT Write a contract test suite spec ~60 MIN
YOU PRODUCEContract test suite specification for one provider and two consumers

Template

# Contract test suite: <provider> with <consumer A>, <consumer B>
Owner · Date · Broker: <url> · Status: draft | piloting | gating

## Scope
Provider: <service, owning team, deploy cadence>
Consumers: <service, owning team, deploy cadence> × 2
Out of scope: <what this suite will not catch, and where it is caught instead>

## Interactions, per consumer
| Consumer | Interaction | Provider state | Request | Fields asserted (matcher) | Read in code at |
|---|---|---|---|---|---|

## Error interactions
| Consumer | Error | Provider state | Status and code | Consumer behaviour |
|---|---|---|---|---|

## Provider states
| State name | Setup | Teardown | Used by |
|---|---|---|---|

## Idempotency and retry tests (integration suite, not the pact)
| Endpoint | Sequential retry | Concurrent duplicate | Same key, different body | Side effect counted at |
|---|---|---|---|---|

## Left to integration tests
- <meaning risk: units, states, ordering> — <test that covers it>

## Third parties
| Dependency | Stubs from | Sandbox check cadence | Owner on failure |
|---|---|---|---|

## Pipeline
- Consumer: publish pact on every build, tagged with <commit / branch>
- Provider: verify on every build and on pact change (webhook)
- Gate: can-i-deploy --to-environment <env> before each deploy; record-deployment after
- Breaking-change process: <who talks to whom before a pact is changed>

## Open questions
| # | Question | Owner | By |
|---|---|---|---|
WORKED EXAMPLE

Saltmarsh is a fictional payment orchestration company: merchants send one API call and Saltmarsh routes it to one of six acquirers. 140 people. The payments API (provider, deploys about eight times a day) has two internal consumers: hosted checkout (deploys daily) and the reconciliation service (deploys weekly, owned by the finance engineering team in another office).

Interactions. Checkout: create intent, confirm intent, fetch intent; asserts id, status (regex over five states), amount_minor (integer), next_action.type. Reconciliation: list captured payments since a cursor, fetch refund; asserts amount_minor, currency (regex [A-Z]{3}), captured_at (ISO 8601), acquirer_ref. Eleven interactions, nine provider states. Verification runs in 70 seconds.

Errors. Checkout branches on 402 card_declined and 409 request_in_flight; both are interactions. Reconciliation branches on 410 for an expired cursor.

Idempotency. Create and confirm each have the three tests, counting authorisations at the acquirer stub; the concurrent test runs 50 times per build.

Left to integration. Amounts: the pact checks amount_minor is an integer, not that it is pence. An integration test runs checkout, payments and reconciliation in containers and asserts a £49.99 payment reconciles to 4999 in the ledger.

Third parties. Acquirer stubs recorded monthly; hourly sandbox check of 30 calls per acquirer, owner the integrations on-call.

Result after one quarter. The broker blocked four provider deploys, each a field reconciliation read that the provider team thought was unused.

Now you

You are the SDET for Kittiwake, a fictional business messaging API, 90 engineers. The provider is the Messages API: businesses send template messages, Kittiwake delivers them over WhatsApp-style channels. Two internal consumers: the campaign scheduler, which sends up to 2 million messages a night with one idempotency key per recipient, and the billing service, which reads delivered-message records and a message.delivered event to charge per conversation. The Messages team plans to rename category to conversation_category next month. Billing has no tests of its own, and its team is six hours ahead of you. The end-to-end suite takes 45 minutes and fails about one run in six for reasons nobody has traced. Last quarter a scheduler retry after a timeout sent 3,000 duplicate messages. Billing charges through Saltmarsh. Write the contract test suite spec. It must cover the event as well as the HTTP calls, say how the rename will be rolled out without breaking billing, and say what you will do about the end-to-end suite.

Self-check

DECIDE

You are the SDET on Kittiwake's billing team. Billing now charges businesses through Saltmarsh, an external payment provider. Saltmarsh has a sandbox with test cards and webhooks; it is rate-limited and was down for six hours last month. The team wants a test plan for the integration before launch in five weeks. The engineering manager asks: do we mock Saltmarsh in our tests, or test against its sandbox?

READING
  1. POST
    Contract Test Martin Fowler, 2011

    The original meaning: tests that check your test doubles against the real service, run on the service's change schedule. Short, and the frame for testing any third party.

  2. POST
    Consumer-Driven Contracts: A Service Evolution Pattern Ian Robinson, 2006

    The pattern Pact implements, argued from service evolution rather than testing. Read it to explain to a provider team why a consumer's expectations should block their build.

  3. DOC
    Pact documentation: introduction Pact Foundation

    What Pact is, consumer-driven contracts, and the case against schema-only testing. Start here, then read How Pact works for the full consumer-to-provider flow.

  4. DOC
    Pact: provider states Pact Foundation

    How to name and implement preconditions so each interaction is verified in isolation. Most brittle pact suites get this wrong first.

  5. DOC
    Pact Broker: Can I Deploy Pact Foundation

    The matrix, the can-i-deploy gate and record-deployment. Read it before you design the pipeline section of your suite spec.

  6. DOC
    Newman CLI overview Postman

    Running collections in CI, including the bail option. Note the page's own advice that Newman is no longer updated and the Postman CLI replaces it.

  7. POST
    Implementing Stripe-like Idempotency Keys in Postgres Brandur Leach, 2017

    How idempotency keys are built server-side, which tells you exactly what to test: recovery points, locked keys, mismatched parameters.

  8. DOC
    Stripe: testing Stripe

    A real payment sandbox's test cards and their limits, including stricter rate limits in test mode. Use it as a model of what a sandbox can and cannot simulate.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Performance and load testing →