Hiep Doan

Contract testing for Spring-boot apps (Part 1)

October 11, 2020

  • contract-testing
  • spring-boot
  • pact

This is the first part of the series about contract testing for Spring-boot microservices apps

What is contract testing?

Contract testing is a set of automated tests that verify the interaction between two services (either through REST API or asynchronous message systems). It is different from unit and integration tests (which verify the operation within one service) and end-to-end test (which aims to validate the operation across UI and possibly multiple internal services).

For the purpose of this post, I’ll only focus on contract testing for Rest API communication.

Concepts

Contract testing centers around the concept of producer and consumer. More concretely, producer is the service that implementing the API endpoint while consumer invokes that endpoint. Thus, one producer can have multiple consumers and contract testing helps to ensure a change in the producer would not break any consumer’s code.

Contract testing is a way to formalize the API specs (i.e how the request and response look like) between producer and consumer and better yet, this contract is verified for any change in consumer and provider’s codebase.

Why is contract testing useful?

With contract testing, producer side can have more confidence to make changes to its implementation that it can be sure that it will not break any consumers’ code.

It also gives more visibility to the producer’s team to know which teams are using the API. For example, if the producer’s team wants to remove a legacy, unused field from its response, the engineers can only have to run the contract tests to see if it fails and in case it fails, which consumer is affected.

It can also help to speed up the development of consumer’s team as they can develop against the contract and at any time, can add a new contract test to verify if the assumption from their side is correct.

Frameworks:

There are two big players in the contract testing space: Pact (https://pact.io/) and Spring Cloud Contract (https://spring.io/projects/spring-cloud-contract). In the next parts, I will implement a small PoC for each framework and discuss the advantages and disadvantages of each integration.

For further reading I can recommend the blog post here: https://martinfowler.com/articles/consumerDrivenContracts.html


Hiep Doan

Written by Hiep Doan, a software engineer living in the beautiful Switzerland. I am passionate about building things which matters and sharing my experience along the journey. I also selectively post my articles in Medium. Check it out!