Getting Started with Contract Test using Spring Cloud Contract

Rajat Mishra
2 min readApr 18, 2022

--

This quick read will help in understanding :

  1. Problem Statement
  2. What is contract testing
  3. Why do we need contract testing
  4. How Spring Cloud Contract can help
  5. Example Repository
  1. Problem Statement

Contract changes in Microservice world.

2. What is contract testing?

Contract testing is a methodology for ensuring that two separate systems (such as two micro services) are compatible and are able to communicate with one other. Contract testing goes beyond schema testing, requiring both parties to come to a consensus on the allowed set of interactions and allowing for evolution over time.

3. Why do we need contract testing?

We currently have 2 major testing approach —

  • Deploy all micro services and perform end-to-end tests.
  • Mock other micro services in unit and integration tests.

Deploy all micro services and perform end-to-end tests

Advantages:

  • Simulates production.
  • Tests real communication between services.

Disadvantages:

  • To test one micro service, we have to deploy all dependant micro services.
  • Operational challenges.
  • They take a long time to run.
  • They are extremely hard to debug.
  • We are testing distributed monolith.

Mock other micro services in unit and integration tests

Advantages:

  • They provide very fast feedback.
  • They have no infrastructure requirements.

Disadvantages:

  • Difficult to maintain.
  • Can give false positives.
  • Mocks creation is slow.

4. How Spring Cloud Contract can help?

To solve the above mentioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the whole world of micro services. If you work on stubs, then the only applications you need are those that your application directly uses.

Note: Spring Cloud Contract’s or PACT purpose is NOT to start writing business features in the contracts. Assume that we have a business use case of credit check. If a user can be a fraud for 100 different reasons, we would assume that you would create two contracts, one for the positive case and one for the negative case. Contract tests are used to test contracts between applications, not to simulate full behaviour.

5. Example Repository

Please take a pull from https://github.com/RajatADP/contract-test.

To implement Spring Cloud Contract in TDD fashion go through the ReadMe.md file inside credit-card(consumer code) repo.

Conclusion

To conclude, all the things listed in this blog are from my personal experience. This document describes a way of how you can start with spring cloud contract.

I would highly recommend to go through the official site which has more details on the topic.

--

--