What is contract testing and why do we need it? - Part 1
What an API contract is, why we need contract testing, how it fits with unit, integration and end-to-end tests, and provider-driven versus consumer-driven approaches.
What is contract testing and why do we need it? - Part 1
Almost every application we build today is a set of services talking to each other through APIs: a web front end calls an API, the API calls other APIs, and some of those APIs are consumed by our customers and partners. Each team tests its own service well, but the most common production issues we see are not inside a service; they are between services. A field gets renamed, a status code changes from 404 to 200 with an empty body, a date format changes, and a consumer which nobody thought about breaks on the next release. In this series, I share how we approach contract testing for our REST APIs, and how we write these tests with the Java library REST Assured. In this article, we are going to see what an API contract is, what contract testing is, how it fits with the other types of tests, and the different approaches to it.
Contract Testing series:
- What is contract testing and why do we need it? (this article)
- How to write API tests with REST Assured?
- How to write contract tests for a REST API with REST Assured?
- Contract testing use cases and best practices
TL;DR Summary
- An API contract is the agreement between a provider and its consumers: URI, verbs, media types, request and response structure, status codes and error format.
- Contract testing verifies that the provider still honors this agreement, without testing the business logic behind it.
- Contract tests are faster and more stable than end-to-end tests, and they catch breaking changes before the consumers do.
- There are two approaches: provider-driven (the provider publishes the contract, e.g. JSON schema or Swagger) and consumer-driven (the consumers publish their expectations, e.g. Pact).
- Test the structure and the semantics of the contract, not the data values which change every day.
Why we need contract testing?
Let us take a simple example. A product API returns the product details, and three consumers use it: our website, our mobile app and a partner’s integration.
{
"success": true,
"data": { "id": "29", "name": "Apple iPhone 6", "price": 500 }
}
One day, the API team renames price to unitPrice for a good reason. All the unit tests of the API pass, because they were updated with the change. The integration tests of the API pass, because they test the API with its own database. The release goes out, and all three consumers start showing an empty price.
Nothing was wrong inside the API. The problem was that the API broke a promise it had made to its consumers, and none of the tests checked that promise. This is the gap contract testing fills.
The usual answer to this problem is end-to-end tests: deploy all the services together and test the user journeys. They do catch such issues, but,
- They are slow, because they need all the services, data and environments to be ready.
- They are flaky, because any service, network or data issue fails the test.
- They come late, often only in the UAT environment, when the fix is expensive.
- They can’t cover the consumers we don’t own, like a partner’s integration.
What is an API contract?
An API contract is the agreement between the provider of an API and its consumers about how they communicate. For a REST API, the contract consists of,
- URI - The resource paths and the query parameters (e.g.
/products/{id}) - Verbs - The HTTP methods supported by each resource (GET, POST, PUT, etc.)
- Media types - The format of the request and response (e.g.
application/json) - Request structure - The fields the provider expects, their types and which ones are mandatory
- Response structure - The fields the provider returns, their types and which ones are always present
- Status codes - What the provider returns for success, client errors and server errors
- Error format - The structure of the error response body
- Headers - Headers which consumers rely on, like
Content-Type,LocationorETag
Simply put, the contract is everything a consumer needs to know to call the API and understand the response, and nothing about how the provider implements it. We discussed these elements in detail in the REST API Design Guidelines series; the uniform interface constraint of REST is, in fact, all about having a shared contract between client and server.
What is contract testing?
Contract testing is a technique to verify that a provider and its consumers can communicate with each other, by testing each side against a shared contract instead of testing them together.
On the provider side, a contract test sends a request to the API and checks that the response honors the contract: the right status code, the right media type, all the mandatory fields with the right types, and the agreed error format. It doesn’t check whether the price is correct; that is the job of the functional tests.
An everyday analogy: think of a power socket and a plug. The socket manufacturer doesn’t test every device in the world; it tests that the socket matches the standard (shape, voltage, frequency). The device manufacturer tests that the plug matches the same standard. As long as both honor the standard, any device works with any socket. The standard is the contract.
Where does contract testing fit?
| Unit tests | Integration tests | Contract tests | End-to-end tests | |
|---|---|---|---|---|
| What it verifies | A unit of code in isolation | A service with its real dependencies (database, etc.) | The interface between a provider and its consumers | A complete user journey across all services |
| Scope | Class or method | One service | One API and its contract | The whole system |
| Speed | Very fast | Medium | Fast | Slow |
| Stability | Very stable | Stable | Stable | Flaky |
| Catches breaking API changes? | No | Rarely | Yes | Yes, but late |
| Owner | Developer | Developer | Provider and consumer teams | QA |
Contract tests don’t replace any of the others. They sit between integration tests and end-to-end tests, and they let us run far fewer end-to-end tests, because the communication between the services is already verified.
Approaches to contract testing
Provider-driven contracts
The provider defines and publishes the contract, for example as a JSON schema or a Swagger (OpenAPI) document, and tests its API against it. The consumers build their clients based on the published contract.
- Good for: Public APIs and APIs with many or unknown consumers, where the provider can’t know every consumer’s expectations.
- Drawback: The provider doesn’t know which parts of the contract each consumer really uses, so every change looks risky, or a risky change looks safe.
Consumer-driven contracts
Each consumer defines what it expects from the provider: the requests it sends and the parts of the responses it uses. These expectations are shared with the provider, and the provider runs them as tests in its own pipeline. Pact (with Pact JVM for Java and Pact libraries for other languages) is the most popular tool for this approach.
- Good for: Internal APIs and microservices, where the provider and consumer teams know each other.
- Drawback: Every consumer has to write and share its contracts, and it needs more coordination and tooling.
Which one to choose?
| Situation | Approach |
|---|---|
| Public or partner API, unknown consumers | Provider-driven |
| Internal API with a few known consumer teams | Consumer-driven, or provider-driven tests written with the consumers’ input |
| Third-party API we consume but don’t own | Consumer-side contract tests against the third-party API |
In this series, we mostly use the provider-driven approach with REST Assured, because it needs no extra infrastructure and it works for both internal and external APIs. In the last article, we will see when to move to consumer-driven contracts.
What to test and what not to test in a contract test
Test,
- The status code for success and for the agreed error cases
- The
Content-Typeand other headers consumers rely on - The presence and the type of the mandatory fields
- The structure of collections (e.g.
datais an array) - The error response format
Don’t test,
- Exact data values which change every day (prices, counts, names)
- Business rules and calculations (they belong to unit and functional tests)
- Performance (it belongs to performance tests)
- The internal implementation of the provider
Must Consider: A contract test which checks data values will fail every time the data changes, and soon nobody will trust it. Test the shape and the meaning of the response, not its content.
Wrap up
In this article, we have looked at why we need contract testing, what an API contract is, what contract testing is, how it fits with unit, integration and end-to-end tests, and the provider-driven and consumer-driven approaches. I really appreciate that you took the time to read this article. In the next article, I will walk you through REST Assured, a Java library to write readable API tests, and how to write your first API test with it.
Related Posts
Postman Environments
Postman environments let us keep one request template for local, dev, qa and production by moving host names and API keys into environment variables, instead of duplicating collections.
Contract testing use cases and best practices - Part 4
Real-world use cases of contract testing, when to move to consumer-driven contracts with Pact, and the best practices and pitfalls we follow.
How to automate API tests with Postman Scripts? - Part 2
Automate API tests with Postman scripts: prepare test cases and data, write tests for real examples and run them with the Collection Runner.