Design First Contract Testing For Micro-services

As we move towards a complex eco-system of modularised services, the concept of Contract testing becomes more and more important. At the same time there’s no single solution for all in the market, thus the choice of contract testing strategy becomes key if you really want to reap the benefits.

At the core, Contract Testing means to agree to a contract (api specs in our case) and then ensure it is adhered to while doing the continuous development

When we develop APIs we might follow different styles to write/maintain them, mainly around who’s initiating the contract design. Three key personas who might come in picture can be —

  • Provider — One who develops the API.
  • API Designer — One who designs the API and gives to Provider to develop.
  • Provider Driven Contract Testing — Where provider writes the contract and consumer tests their implementation against it.
  • Design First Contract Testing — Where API Designer creates a contract and both Consumer and Provider test their implementation against it.
Consumer Driver Contract Testing with PACT
Design First Contract Testing Using Swagger Hub
  • SwaggerHub (or any API design tool) works like a Broker being a contract store (api spec store) which is the single source of truth in the entire chain.
  • Producer/Provider pulls the API spec at runtime and validates them against their implementation. This is quite similar to PACT where Provider pulls the contract at runtime from Broker and checks implementation against it.
  • Consumer interacts with the mock generated against the API specs from Swagger Hub, and validate their consumption code with it. This is also similar the PACT where consumer validates their consumption code against the in-memory mock-server generated at runtime.

SwaggerHub provides the mock server out of the box — See here to explore more

Step 1 — Design API (API Designer)

Start Designing your API in SwaggerHub. SwaggerHub gives you an easy interface to design the APIs and share the documentation with others to refer to.

Step 2 — Implement and Validate API Specs (Provider)

Let’s create a simple endpoint say /products which gives the list of products available in the system

<dependency>   
<groupId>com.atlassian.oai</groupId>
<artifactId>swagger-request-validator-mockmvc</artifactId>
<version>2.18.0</version>
</dependency>

Step 3— Validate API (Consumer)

Like we discussed before, SwaggerHub provides the mock-endpoint for your specifications out of the box. See here for details.

Developer at ThoughtWorks