Search Sreeni's Insights

Filter by content type
crafting November 6, 2018 8 min read

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.

Share:

Contract testing use cases and best practices - Part 4

Contract tests pay off most in the places where a broken promise is expensive: many consumers, consumers we don’t control, independent release cycles, or APIs we depend on but don’t own. Knowing these places helps us decide where to invest first, and the best practices help us keep the tests valuable as the APIs grow. In the previous article, we discussed how to define the contract of an API and write contract tests for it with REST Assured. In this last article of the series, we are going to see the real world use cases of contract testing, when to move to consumer-driven contracts with Pact, and the best practices and common pitfalls.

Contract Testing series:

  1. What is contract testing and why do we need it?
  2. How to write API tests with REST Assured?
  3. How to write contract tests for a REST API with REST Assured?
  4. Contract testing use cases and best practices (this article)

TL;DR Summary

  • Contract testing gives the most value for microservices, public APIs, third-party APIs we depend on, API versioning and post-deployment checks.
  • Move to consumer-driven contracts (Pact) when you have several known consumer teams and want to know exactly which changes affect whom.
  • Define the contract first, keep the schemas in source control, and review every contract change in the pull request.
  • Test the shape and the meaning of the response, not the data; test the error contract; allow additional fields.
  • Keep contract tests few, fast and focused, and run them on every deployment.

Use cases

1. Microservices with independent releases

Problem: Each service is released by its own team, on its own schedule. Running the full end-to-end test suite for every release of every service is slow, and coordinating the releases defeats the purpose of microservices.

How contract testing helps: Each provider runs its contract tests on every build. When the contract is honored, the service can be released independently, with confidence that its consumers won’t break.

2. Promoting internal APIs to external users

Problem: When an internal API is opened to customers and partners, its contract becomes a public promise. We don’t know all the consumers anymore, and we can’t ask them before a change.

How contract testing helps: The provider-driven contract (JSON schemas and the Swagger document) is published with the API, and the contract tests become a release gate. No change which breaks the published contract can go out without a new version. Refer to the Promoting Internal APIs series for the other aspects of opening an API.

3. Third-party APIs we depend on

Problem: We consume APIs from vendors and partners, and they change their APIs on their own schedule, sometimes without telling us. We find out when our application breaks.

How contract testing helps: Write consumer-side contract tests for the parts of the third-party API we use, and run them on a schedule (for example, every night) against the vendor’s API. When the vendor changes something we depend on, we know the next morning, not from a customer complaint.

@Test
public void vendorPricesApi_shouldHonorTheFieldsWeUse() {
    given()
        .baseUri("https://<vendor api host>")
        .header("Authorization", "Bearer <vendor api token>")
    .when()
        .get("/prices/<sample instrument id>")
    .then()
        .statusCode(200)
        .body("price", notNullValue(),
              "currency", notNullValue(),
              "priceDate", notNullValue());
}

Only test the fields we use; the vendor is free to change the rest.

4. API versioning

Problem: When an API has multiple versions running at the same time, a change for v2 can accidentally break v1, which the existing consumers still use.

How contract testing helps: Keep a set of contract tests (and schemas) for each supported version, and run all of them on every build. The v1 tests keep running until v1 is deprecated and removed. Refer to the versioning section of REST API Design Guidelines - Part 6.

5. Post-deployment checks

Problem: The deployment succeeded, but is the API in production really honoring its contract? A configuration difference between environments can still break the response.

How contract testing helps: Run the read-only contract tests as part of the smoke test after each deployment, including production. They are fast, they don’t change any data, and they verify exactly what the consumers depend on. Refer to the CI/CD Process series for where the smoke tests fit.

6. Front end and back end built in parallel

Problem: The front end team waits for the API to be ready, or builds against assumptions which turn out to be wrong.

How contract testing helps: Both teams agree on the contract (the JSON schemas) first. The front end team builds against a mock which returns responses matching the schema, and the back end team builds the API until the contract tests pass. When both are ready, they fit together.

When to move to consumer-driven contracts?

So far, we used provider-driven contracts: the provider defines the contract and tests against it. This works well, but it has one blind spot: the provider doesn’t know which parts of the contract each consumer really uses. Consumer-driven contracts close this gap.

How consumer-driven contracts work with Pact

  1. Consumer test - The consumer team writes a test for its API client against a mock provider, describing the requests it sends and the responses it expects (only the fields it uses).
  2. Pact file - Running the consumer test generates a contract file (a “pact”) with these expectations.
  3. Share - The pact file is shared with the provider team, usually through a Pact Broker.
  4. Provider verification - The provider’s pipeline replays the requests from all the pact files against the real API, and checks that the responses meet each consumer’s expectations.
  5. Feedback - When a provider change breaks a consumer’s expectation, the provider’s build fails, and the provider knows exactly which consumer would break.

For Java, Pact is available as Pact JVM, and there are Pact libraries for .NET, JavaScript and other languages, so the consumer and the provider don’t have to use the same one.

Provider-driven vs consumer-driven

Provider-driven (e.g. REST Assured + JSON schema)Consumer-driven (e.g. Pact)
Who writes the contractProviderEach consumer
Knows which consumer uses whatNoYes
Works for unknown consumersYesNo
Extra infrastructureNonePact Broker (recommended)
Coordination between teamsLowHigher
Best forPublic APIs, few consumers, getting startedInternal microservices with several known consumer teams

Our recommendation: start with provider-driven contract tests, because they need no extra infrastructure and give value from day one. Move to consumer-driven contracts for the internal APIs with several consumer teams, when the question “who will break if we change this?” comes up often.

Best practices

  • Define the contract first. Agree on the contract with the consumers before implementing the API, and write it down as schemas.
  • Keep the schemas in source control, next to the API and its tests, and review every change to them in the pull request. A change to a schema is a change to a promise.
  • Test the shape and the meaning, not the data. Check types, required fields, status codes and relationships (like “the id we asked for is the id we got”), not values which change every day.
  • Test the error contract. Consumers write code for 404 and 400 as well; test them as carefully as the success cases.
  • Allow additional fields. Adding a field should not fail the contract tests; removing, renaming or changing the type of a field should.
  • Don’t hard-code test data. Take the ids and other inputs from the API itself (like the product list), so the tests don’t break when the data changes.
  • Keep contract tests few, fast and focused. One or two tests per API function are usually enough; leave the business scenarios to the functional tests.
  • Give the tests meaningful names. The name is what you see in the build report, so make it say which promise was broken.
  • Run them on every deployment, and don’t promote a build which breaks the contract.
  • Share the contract with the consumers. Publish the schemas or the Swagger document, so the consumers build against the same contract you test.

Common pitfalls

PitfallWhy it hurtsInstead
Asserting exact data valuesThe tests fail every time the data changes, and the team stops trusting themAssert types, presence and relationships
additionalProperties: false everywhereEvery new field becomes a “breaking” changeAllow additional fields, unless the contract really forbids them
Testing business logic in contract testsThe tests become slow, fragile and duplicate the functional testsKeep contract tests to the interface
Only testing the happy pathError format changes break consumers silentlyTest the agreed error cases
Contract tests that nobody runsThey give false confidenceRun them in the pipeline on every deployment
Treating contract tests as a replacement for end-to-end testsSome user journeys still need to be tested as a wholeUse contract tests to reduce, not remove, end-to-end tests

Wrap up

In this article, we have looked at the real world use cases of contract testing, how consumer-driven contracts work with Pact and when to move to them, and the best practices and common pitfalls. With this, we have completed the Contract Testing series: from what an API contract is and why we need contract testing, writing API tests with REST Assured, writing contract tests for a real API, to the use cases and best practices. I really appreciate that you took the time to read this series. I hope it helps you to catch the broken promises between your services in the build pipeline, before your consumers do.

Related Posts