Contract Tests with Spring Cloud Contract

Contract tests has a lot of significance and value in Micorservices world. You can keep fixing your end to end or integration tests, which runs very late in the build, are difficult to debug and cost lot of resources to maintain.

Component tests are good for testing integration between the various components of an API. However, in microservices world there are a number of APIs that serves different/unique purposes and are part of an application/system. Component tests alone can’t assure that integration between micorservices is working fine.

In case of Integration tests, testing  a change in one API can lead to horrible time consuming process of setting up all the APIs, databases, brokers etc. Using Docker instances and Docker compose for orchestration makes things a little easier, however, it comes with a cost of maintaining your docker images and docker-compose files.

Contract tests not only ensures that two APIs will behave nicely with each other, they also fail fast. Which means the moment a developer makes a change in an API (Producer) that can break other APIs (Consumers), the developer will get to know right there on his local setup. Consumer APIs will know for sure when they run the tests on any CI pipeline (Jenkins, CircleCI). 

Why I said that contract tests can do magic is because of couple of reasons:
  1. You don’t have to setup other microservices, brokers or database to test integration between micorservices. You can however, choose to use database for assertions in some cases, however no other services are required.
  2. A contract (not contract test), gets first executed on the Producer API, and ensures that the applications behaves the way contract says. Which means both the contract and code has to be in sync. In a way, some component tests are autogenerated which tests the API and ensures validness of input and output. You are getting code coverage as a byproduct.
  3. Finally, when you are writing component tests on the consumer side, you don’t need to mock the external APIs. You will get qualified stubs which represents the API. And these stubs are much more reliable that the mocks.



Overall, contract tests gives you a reliability of end to end tests and speed of Unit tests. Best of both worlds. 

Comments

Popular posts from this blog

Spring Security - Adding more information to the authenticated user.

Hibernate Difference between update() and merge()

Running tomcat maven plugin in Debug mode (in STS, Eclipse and MyEclipse)