Skip to content

API contract testing: when consumer-driven contracts pay off

B2Bnetwork team · · 6 min

Testing and quality

In brief

A contract test checks whether the two sides of an integration, the API consumer and provider, agree on the format of requests and responses without running them together. In the consumer-driven approach the contract comes from the consumer's tests, and the provider verifies it on its side. It pays off when several teams develop services independently and deploy them separately. With a single team, a monolith or a public API with unknown clients, the benefit is small.

What problem contract tests solve

In an architecture with many services, the interfaces cause the most trouble. The accounts service team renames a field, unit tests are green, and the mobile app stops displaying the balance. The defect surfaces only on the shared integration environment or in production.

The classic answer is E2E tests on an environment with all the services. They have three drawbacks: the environment is expensive and often unavailable, the tests are slow and flaky, and a failure does not say which team broke something. Contract tests move this check lower in the test pyramid: each side verifies its part of the agreement separately, in its own pipeline, in a few seconds.

How the consumer-driven approach works

In the consumer-driven approach the sequence is as follows:

  1. The consumer writes a test of its API client against a provider mock. The test describes a specific request and the response the consumer expects, for example fetching an account and the fields `iban`, `saldo`, `waluta`.
  2. The test produces a contract, a file with example interactions. It goes into a shared contract repository, called the broker.
  3. The provider verifies the contract in its pipeline: a tool replays the requests from the contract against the running provider service and compares the responses.
  4. Before deployment each side checks that its version is compatible with the other side's versions that are on the target environment.

The best-known tool is Pact. Its documentation describes it as a code-first tool for contract testing HTTP and message integrations, in which the contract is created during consumer tests. A Pact contract is a “contract by example”: each test describes one specific request and response pair. Pact has a broker for storing contracts and verification results, and a `can-i-deploy` tool that answers whether a given service version can be safely deployed.

An important property of this approach: the provider tests only what consumers actually use. A field nobody reads can be changed or removed without breaking the contract, and a field used by the mobile app is protected even if the provider team does not remember it.

Contract by example vs. an OpenAPI schema

An OpenAPI specification describes the provider's whole interface: all paths, fields, types. A consumer-driven contract describes only what a specific consumer uses, on specific examples. It is a complement, not a replacement.

AspectOpenAPI schemaConsumer-driven contract
Who creates itThe providerThe consumer, from its tests
What it describesThe whole interfaceInteractions used by a given consumer
What it checksConformance to the schemaConformance to expected behavior on examples
Detects a change in semanticsNo, if the type matchesYes, if the example shows what the value means
Good forPublic APIs, documentation, client generationMany teams within one organization

An example of the difference: the `status` field is a string in both versions of the API, so schema validation passes. But the new version returns `ZAKSIEGOWANY` instead of `WYKONANY`. A contract with a sample response will detect the change, a schema will not.

There is also a provider-driven approach: the provider publishes a contract, from which mocks are generated, and consumers check their code against them. This approach works when the provider has many consumers and does not want to make its releases dependent on each of them.

When it pays off and when it does not

Consumer-driven contract tests work best when:

  • several teams develop services that talk to each other, and each deploys them separately;
  • the shared integration environment is a bottleneck or often unavailable;
  • consumer and provider teams belong to one organization and can agree on a shared process;
  • integrations run over HTTP or through messages in queues, for example events in Kafka.

The benefit is small or zero when:

  • one team develops both ends of the integration and deploys them together;
  • the API is public and the provider does not know its consumers. Then a schema, versioning and backward compatibility tests are better;
  • the provider is an external system, for example a settlement system or a partner service that will not run your contracts on its side. What remains are integration tests on the partner's test environment and mocks based on its documentation;
  • the goal is to check the provider's business logic. A contract checks the shape and meaning of the response, not whether the balance was calculated correctly.

How to introduce contract testing in an organization

It is best to start with one pair of services that causes the most problems on the integration environment:

  1. The consumer team writes a few contract tests for the most important interactions.
  2. The provider team adds verification to its pipeline, with data prepared for each interaction (in Pact these are called provider states).
  3. Results go to the broker, and the version compatibility check becomes a deployment condition.
  4. After a few weeks the team evaluates how many integration defects the contract caught before they reached the shared environment, and decides on extending it to more services.

The hardest part is organizational, not technical. The provider team must accept that a failed contract verification blocks its release, and agree with consumers how to negotiate changes. Without that agreement, contract tests are quickly switched off as “getting in the way”. Choosing an API style is covered in the article REST, GraphQL or gRPC, and introducing contract tests at a bank in the case study API and contract test automation in an internet banking microservices program.

Questions and answers

Do contract tests replace integration tests?

Partially. They replace a large share of tests that check only whether two sides understand each other. They do not replace tests that check cooperation with a real database, queue or external system, or a few E2E tests of critical paths. In practice, after introducing contracts the E2E layer shrinks, and the integration environment is used for end-to-end rehearsals, not for detecting field changes.

Do contract tests work with asynchronous messages?

Yes. According to its documentation, Pact supports HTTP integrations and message-based integrations. The consumer describes what message it expects, and the producer verifies that its code generates a message matching the contract. This does not check the queue infrastructure itself, only the content and structure of the message, which in an event-driven architecture is a common source of defects.

Who owns the contract?

In the consumer-driven approach the consumer writes the contract, but responsibility is shared. The consumer is responsible for describing only what it really uses. The provider is responsible for making sure its release does not break verified contracts. A change that has to break a contract is agreed on by the teams in advance, for example through a transition period with two versions of a field.

How much work does introducing contract tests take?

For one pair of services, usually a few days of work by the consumer and provider teams, plus setting up the broker. The biggest cost is the process change: adding verification to pipelines and the rule that the compatibility check blocks deployment. The return comes when there are many integrations and they change often. With two stable services the effort may not pay off.

What it looks like in a project

Planning testing for your project? Talk to a test manager.

Let's talk

Read more: Testing and quality