Using Spring Cloud Contract for Consumer Driven Contracts

Consumer Driven Contracts are considered a design pattern for evolving services. Spring Cloud Contract can be used to implement consumer driven contracts for services developed using the Spring Framework.

In this post, I’ll take an in depth look at using Spring Cloud Contract to create Consumer Driven Contracts.

An Overview of Spring Cloud Contract

Let’s consider a typical scenario where a consumer sends a request to a producer.

If you were working on the API consumer, how can you write a test without creating a dependency on the API producer?

One tool you can use is WireMock. In WireMock, you define stubs in JSON and then test your consumer calls against the stubs.

By using a tool like WireMock, when developing the consumer side code, you break any dependency on the producer implementation.

Here is an example WireMock stub.

This WireMock stub definition says that given a request of method POST sent to URL gamemanagerwith a query parameter game and a request body, we would like a response of status 200 with JSON in the body.

Spring Cloud Contract allows you to write a contract for a service using a Groovy or YAML DSL. This contract sets up the communication rules, such as the endpoint address, expected requests, and responses for both the service provider and consumer.

Spring Cloud Contract provides plugins for Maven and Gradle to generate a stubs from a contracts. These are WireMock stubs like the example above.

The consumer side of the application can then use the stubs for testing.

For the producer side, Spring Cloud Contract can generate unit tests which utilize Spring’s MockMVC.

Its important to maintain the distinction between consumer and producers. Spring Cloud Contract is producing testing artifacts which allow the development of the consumer side code and the producer side code to occur completely independently.

This independence is very important. On small projects, its fairly common for a developer or small team to have access to the course code for both consumer and producer.

On larger projects, or when dealing with third parties, often you will not have access to both sides of the API.

For example, you may be a Spring developer providing an API for the UI team to write against.  By providing WireMock stubs the UI team can run the stubs for their development. The client side technology does not need to be Spring or even Java. They could be using Angular or ReactJS.

The WireMock stubs can be run in a stand-alone server, allowing any RESTful client to interact with the defined stubs.

Let’s take a closer look at the process by setting up a Producer and Consumer.

The Initial Producer

Let’s say the Producer is in development.

Right now, the Producer does not have any implementation code but only the service contract in form of Groovy DSL.

The Maven POM

Before we start writing the contracts, we need to configure Maven.

We need to include the spring-cloud-starter-contract-verifier as a Maven dependency.

We also need to add spring-cloud-dependencies in the section of our Maven POM.

Finally, Spring Cloud Contract provides plugin for both Maven and Gradle that generates stubs from DSLs.

We need to include the plugin in our Maven POM.

Here is the complete pom.xml of the Producer.


The Spring Cloud Contract Groovy DSL

Spring Cloud Contract supports out of the box two types of DSLs: Groovy and YAML.

In this post, I will use Spring Cloud Contract Groovy DSL. DSL or Domain specific language is meant to make the code written in Groovy human-readable. 

Currently our Producer, the Game Manager is responsible for allowing a player with a score greater than 500 to play a game of football. Any player with a score less than 500 is not allowed to play the game.

Our first contract defines a successful POST request to the Game Manager.

Here is the game_contract_for_score_greater_than_500.groovy DSL.


The other contract defines a POST request to the Game Manager for a score lesser thn 500. The game_contract_for_score_lesser_than_500.groovy DSL is this.


As you can see the DSLs are intuitive. The code imports the Contract class and calls the make method. The contract, in addition to the contract name and description has two parts: request and response.

For this example, we have hardcoded the request values. However, Groovy DSL supports dynamic values through regular expressions. More information here.

The Consumer

The consumer will have a REST controller that receives requests for playing game. The consumer needs to verify with the Game Manager before starting the game by making a request to it.

On the consumer side, fork or clone the producer and run this command.

On running the command, the Spring Cloud Contract Maven plugin does two things:

  1. Converts the Groovy DSL contracts into a WireMock stub.
  2. Installs the JAR containing the stub into your Maven local repository

NOTE: In a typical enterprise situation where the consumer is a different team, the JAR artifact would typically be published to an internal maven repository.

This figure shows the generated stub in the Project window of IntelliJ.
Generated Stub

We are now ready to implement the consumer.

The Maven POM

One of the tool that the consumer needs is the stub runner, which is part of the Spring Cloud Contract project. Stub runner is responsible for starting up the producer stub on the consumer side. This enables the consumer to make requests to the stub offline and do all necessary testing before going live in production.

The code to include the stub runner dependency in the Maven POM is this.

We will also use Project Lombok, a Java library that auto generates boilerplate code based on annotations you provide in your code. The Lombok dependency declaration in the Maven POM is this.

The complete Maven POM on the consumer side is this.


The Domain Object

We will model a player as a domain object on the consumer side.

Here is the code for the Player class.

I’ve used Lombok annotations on the Player class. As you can see the class is much cleaner and only focuses on the properties it represents.

The @Data Lombok annotations will generate the getter, setter, toString(), hashCode(), and equals() method for us during the build.

The @AllArgsConstructor and @NoArgsConstructor will add a constructor to initialize all properties and a default constructor for us.

The @Builder annotation will add builder APIs based on the Builder pattern for your class.

When you build the Player class, you will get an equivalent class with the Lombok generated code, like this.

The Tests

Next let’s go with the TDD approach and write the tests first. We will begin with an abstract test class, AbstractTest.

This code initializes a JacksonTester object with an ObjectMapper that we will next use to write JSON data to test our controller.

Next is our controller test class. I have used Spring Boot Test and JUnit. I have a post on Spring Boot Test which you should go through if you are new to it. Also, if you are new to JUnit, I suggest you go through my JUnit series of posts.

The controller test class, is this.

In this code:

  • Line 20: Specifies SpringRunner as the test runner.
  • Line 21 bootstraps the test with Spring Boot’s support. The annotation works by creating the ApplicationContext for your tests through SpringApplication. The webEnvironment.MOCK attribute configures the “web environments” to start tests with a MOCK servlet environment.
  • Line 22 auto configures MockMvc to be injected for us. MockMvc in the test will be providing a mock environment instead of the full blown MVC environment that we get on starting the server.
  • Line 23 enable auto-configuration of JSON tester that we wrote earlier in AbstractTest.
  • Line 24 is important. Here we used @AutoConfigureStubRunner to instruct the Spring Cloud Contract stub runner to run the producer stub online. If you recall, we installed the producer stub in Maven local. The ids attribute specifies the group-ID and artifact-ID of the stub and instructs to start the stub on port 8090.
  • Line 25 @DirtiesContext indicates that the ApplicationContext associated with the test is dirty and should be closed. Thereafter, subsequent tests will be supplied a new context.
  • Line 27 – 29 autowires in MockMvc and the GameEngineController under test.
  • Line 33 – 44 uses MockMVC to test the controller for a Player with score greater than 500.
  • Line 48 – 60 is the second test case that uses MockMVC to test the controller for a Player with score lesser than 500.

When you run the tests, as expected they fails. This is the first step in TDD where you write your tests first and see them fail.

The Controller Implementation

The controller for the Game Engine consumer is a REST controller with a single endpoint. We will implement the controller to make a REST request to the Producer stub in compliance with the Spring Cloud Groovy DSL contract.

Although in a real project, you will have a service layer making the REST request, for the sake of demonstration, I am doing it from the controller itself.

The controller code is this.

The controller code uses a Spring injected RestTemplate to make a POST request to the producer stub and return back the response string as a ResponseEntity.

If you run the controller tests now, the tests pass.
Test Output of Spring Cloud Contract

Contract Violation

Let’s consider a scenario where the consumer violate the producer contract. To simulate this, we will update the test cases to do two things:

  1. Send a Person initialized only with the score field.
  2. Introduce a typo in the request URL.

Here is the code of the updated test cases.

In the first test case, we commented out the statement that sets the player name. In the second test case we intentionally introduced a typo in the request URL as /play/footballs instead of /play/football.

When we run the tests fail, as shown in this figure.

Test Output Contract Violation

As we can see, with Spring Cloud Contract we are enforcing certain set of rules that we expect consumers to follow. A consumer violating any rule fails the tests.

When you are working in cloud native architecture with CI and CD pipeline configured, this test failure will break your CI build. As a result, consumer code violating the contract would never get deployed to production.

Producer Tests

Coming back the the Producer side of the contract, Spring Cloud Contract will also generate unit tests.

The generated tests are build from a base class. This allows you a lot of flexibility in how your tests are setup. And a minimum, you will need to mock the controller under test.

Recall the following configuration of Maven:

Here, in the configuration we are defining the base class for the tests.

Producer Base Test

Here is our implementation of the base class. This is a very minimal implementation. A more complex example could involve mocking services with Mockito.

For the test base class, I also added a controller, which is just an empty class.

Spring Cloud Contract Generated Tests

Spring Cloud Contract will generate tests for our controller from the contracts we have defined.

In the example we have been following, the following tests are generated.

You can see in the above example, the generated test class extends from the base class we configured and implemented.

If your following TDD, you would now have failing tests, and you would go and complete the implementation of the Game controller.

If you execute tests (mvn clean install), you will see the following output, showing the failing tests.


In these examples, I’ve only shown a few highlights of using Spring Cloud Contract. The project is very robust and offers rich functionality.

If you are building or consuming APIs developed by others, using Consumer Driven Contracts is a tool you can use to improve the quality of your software. And to avoid unexpected breaking changes.


You May Also Like

Leave a Reply