Search Sreeni's Insights

Filter by content type
crafting October 23, 2018 6 min read

How to write contract tests for a REST API with REST Assured? - Part 3

Define the contract of a REST API, express it as JSON schemas and write contract tests with REST Assured that catch breaking changes but allow additive ones.

Share:

How to write contract tests for a REST API with REST Assured? - Part 3

Knowing the tool is half of the job; the other half is deciding what exactly the contract is and turning it into tests which fail only when the contract is broken. A contract test which fails every time the data changes is noise, and a contract test which passes when a field disappears is false confidence. In the previous article, we discussed REST Assured and how to write API tests with it. In this article, we are going to define the contract of the ZYX Commerce product API, write contract tests for it with REST Assured and JSON schemas, and see how these tests catch a breaking change while allowing a non-breaking one.

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? (this article)
  4. Contract testing use cases and best practices

TL;DR Summary

  • Write the contract down first: the status codes, the headers, the response structure and the error format for each API function.
  • Express the response structure as a JSON schema, and validate every response against it.
  • Test the error contract (like 404 for an unknown id) as carefully as the success contract.
  • Allow additional fields in the schema, so adding a field is not treated as a breaking change, while removing or renaming a field is.
  • Run the contract tests in the build pipeline after every deployment to the Dev environment.

Step 1: Define the contract

Before writing any test, we write the contract down. For the ZYX Commerce product API, the contract looks like this.

Product list - GET /products

ElementContract
Status code200
Content-Typeapplication/json
Bodysuccess (boolean, always true) and data (array of products)
Productid (string), name (string), description (string), price (number), categories_ids (string)

Product details - GET /products/{id}

ElementContract
Status code200 for a known id, 404 for an unknown id
Content-Typeapplication/json
Body (200)success (boolean, true) and data (one product, same structure as above)
Body (404)success (boolean, false), message (string) and data (empty object)

Writing the contract down is a valuable exercise on its own. In our experience, it is the first time the provider and consumer teams agree on details like “is id a string or a number?” or “what does the API return for an unknown id?”.

Must Consider: Ask the consumer teams which fields they actually use. A field nobody uses can change freely; a field every consumer uses needs a versioning plan before it changes.

Step 2: Express the response structure as JSON schemas

A JSON schema describes the structure of a JSON document: which fields exist, their types and which ones are required. It is a precise and machine-readable way to write the contract.

Create a schemas folder under src/test/resources in the test project and add the following files. Anything under src/test/resources is on the test classpath, so the tests can load the schemas by name.

schemas/product-details.json - the product details response,

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["success", "data"],
  "properties": {
    "success": { "type": "boolean", "enum": [true] },
    "data": {
      "type": "object",
      "required": ["id", "name", "description", "price", "categories_ids"],
      "properties": {
        "id": { "type": "string" },
        "name": { "type": "string" },
        "description": { "type": "string" },
        "price": { "type": "number" },
        "categories_ids": { "type": "string" }
      }
    }
  }
}

schemas/product-list.json - the product list response,

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["success", "data"],
  "properties": {
    "success": { "type": "boolean", "enum": [true] },
    "data": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["id", "name", "description", "price", "categories_ids"],
        "properties": {
          "id": { "type": "string" },
          "name": { "type": "string" },
          "description": { "type": "string" },
          "price": { "type": "number" },
          "categories_ids": { "type": "string" }
        }
      }
    }
  }
}

schemas/error.json - the error response,

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["success", "message", "data"],
  "properties": {
    "success": { "type": "boolean", "enum": [false] },
    "message": { "type": "string" },
    "data": { "type": "object" }
  }
}

Notice two choices in these schemas,

  • No additionalProperties: false - The provider can add new fields without breaking the contract. Consumers must ignore the fields they don’t know (refer to the versioning section of REST API Design Guidelines - Part 6).
  • Types, not values - We check that price is a number, not that it is 500. The data can change every day; the contract shouldn’t.

Step 3: Write the contract tests

The json-schema-validator dependency (added in the previous article) provides matchesJsonSchemaInClasspath, a Hamcrest matcher which loads a schema from the classpath and validates the response body against it. Add the base class for the host and port (from the previous article) and write the tests.

import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

Product list contract

public class ProductListContractTests extends ApiTestBase {

    @Test
    public void productList_shouldHonorTheContract() {
        given()
            .header("Accept", "application/json")
        .when()
            .get("/products")
        .then()
            .statusCode(200)
            .contentType(containsString("application/json"))
            .body("data.size()", greaterThan(0))
            .body(matchesJsonSchemaInClasspath("schemas/product-list.json"));
    }
}

Product details contract

public class ProductDetailsContractTests extends ApiTestBase {

    @Test
    public void productDetails_knownId_shouldHonorTheContract() {
        // Arrange: take a real id from the list, instead of hard-coding test data
        String productId = given()
            .when().get("/products")
            .then().statusCode(200)
            .extract().path("data[0].id");

        given()
            .header("Accept", "application/json")
        .when()
            .get("/products/" + productId)
        .then()
            .statusCode(200)
            .contentType(containsString("application/json"))
            .body("success", equalTo(true))
            .body("data.id", equalTo(productId))
            .body(matchesJsonSchemaInClasspath("schemas/product-details.json"));
    }

    @Test
    public void productDetails_unknownId_shouldReturnTheErrorContract() {
        given()
            .header("Accept", "application/json")
        .when()
            .get("/products/does-not-exist")
        .then()
            .statusCode(404)
            .contentType(containsString("application/json"))
            .body(matchesJsonSchemaInClasspath("schemas/error.json"));
    }
}

A few things to notice,

  • The “known id” test takes the id from the product list instead of hard-coding it. The test doesn’t break when the test data changes.
  • The “unknown id” test checks the error contract. Consumers write code for the error cases too, so a change from 404 to 200 with an empty body is as breaking as a renamed field.
  • data.id equal to the requested id checks a relationship (the id we asked for is the id we got), not a data value. This is part of the meaning of the contract.

Note: The schemas declare JSON schema draft-04, which the json-schema-validator module supports. The contract and the schemas are plain JSON, so any other consumer of the contract can reuse the same files.

Step 4: See the contract tests in action

Let us see how the tests behave for two changes to the API.

A non-breaking change: adding a field

The API team adds a new currency field to each product.

{ "id": "29", "name": "Apple iPhone 6 [demo]", "price": 500, "currency": "GBP", ... }

All the contract tests still pass. The schema allows additional fields, and the existing consumers simply ignore the new one. The API can evolve without a new version.

A breaking change: renaming a field

The API team renames price to unitPrice.

{ "id": "29", "name": "Apple iPhone 6 [demo]", "unitPrice": 500, ... }

The product list and product details contract tests fail, because price is a required field in both schemas. The test report tells exactly which test failed and why, and the change is caught in the build pipeline, not by the consumers in production.

At this point, the team has two options: keep price (and add unitPrice alongside it, if needed), or release the change as a new major version of the API and give the consumers time to migrate.

ChangeContract test resultBreaking?
Add a new fieldPassNo
Remove or rename a fieldFailYes
Change a field type (e.g. id from string to number)FailYes
Change the status code for an unknown idFailYes
Change a data value (e.g. a price)PassNo

Step 5: Run the contract tests in the pipeline

Contract tests give the most value when they run automatically on every change.

  1. The CI build compiles and runs the unit tests.
  2. The CD pipeline deploys the build to the Dev environment.
  3. The contract tests run against the Dev environment (pass -Dapi.host and -Dapi.port to mvn test for it).
  4. When a contract test fails, the build is not promoted to QA.

Refer to the CI/CD Process series for where these tests fit in the end-to-end workflow.

Wrap up

In this article, we have looked at how to define the contract of the ZYX Commerce product API, express the response structure as JSON schemas, write contract tests for the success and error cases with REST Assured, how these tests catch a breaking change while allowing a non-breaking one, and where they run in the pipeline. I really appreciate that you took the time to read this article. In the next article, I will walk you through the real world use cases of contract testing, when to move to consumer-driven contracts, and the best practices we follow.

Related Posts