I just announced the new Spring 5 modules in REST With Spring:


1. Introduction

Spring Cloud Contract is a project that, simply put, helps us write Consumer-Driven Contracts (CDC).

This ensures the contract between a Producer and a Consumer, in a distributed system – for both HTTP-based and message-based interactions.

In this quick article, we’ll explore writing producer and consumer side test cases for Spring Cloud Contract through an HTTP interaction.

2. Producer – Server Side

We’re going to write a producer side CDC, in the form of an EvenOddController – which just tells whether the number parameter is even or odd:

public class EvenOddController {

    public String isNumberPrime(@RequestParam("number") Integer number) {
        return Integer.parseInt(number) % 2 == 0 ? "Even" : "Odd";

2.1. Maven Dependencies

For our producer side, we’ll need the spring-cloud-starter-contract-verifier dependency:


And we’ll need to configure spring-cloud-contract-maven-plugin with the name of our base test class, which we’ll describe in the next section:


2.2. Producer Side Setup

We need to add a base class in the test package that loads our Spring context:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class BaseTestClass {

    private EvenOddController evenOddController;

    public void setup() {
        StandaloneMockMvcBuilder standaloneMockMvcBuilder 
          = MockMvcBuilders.standaloneSetup(evenOddController);

In the /src/test/resources/contracts/ package, we’ll add the test stubs, such as this one in the file shouldReturnEvenWhenRequestParamIsEven.groovy:

import org.springframework.cloud.contract.spec.Contract
Contract.make {
    description "should return even when number input is even"
        method GET()
        url("/validate/prime-number") {
            queryParameters {
                parameter("number", "2")
    response {
        status 200

When we run the build, the plugin automatically generates a test class named ContractVerifierTest that extends our BaseTestClass and puts it in /target/generated-test-sources/contracts/.

The names of the test methods are derived from the prefix “validate_” concatenated with the names of our Groovy test stubs. For the above Groovy file, the generated method name will be “validate_shouldReturnEvenWhenRequestParamIsEven”.

Let’s have a look at this auto-generated test class:

public class ContractVerifierTest extends BaseTestClass {

public void validate_shouldReturnEvenWhenRequestParamIsEven() throws Exception {
    // given:
    MockMvcRequestSpecification request = given();

    // when:
    ResponseOptions response = given().spec(request)

    // then:
    // and:
    String responseBody = response.getBody().asString();

The build will also add the stub jar in our local Maven repository so that it can be used by our consumer.

Stubs will be present in the output folder under stubs/mapping/.

3. Consumer – Client Side

The consumer side of our CDC will consume stubs generated by the producer side through HTTP interaction to maintain the contract, so any changes on the producer side would break the contract.

We’ll add BasicMathController, which will make an HTTP request to get the response from the generated stubs:

public class BasicMathController {

    private RestTemplate restTemplate;

    public String checkOddAndEven(@RequestParam("number") Integer number) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");

        ResponseEntity<String> responseEntity = restTemplate.exchange(
          "http://localhost:8090/validate/prime-number?number=" + number,
          new HttpEntity<>(httpHeaders),

        return responseEntity.getBody();

3.1. The Maven Dependencies

For our consumer, we’ll need to add the spring-cloud-contract-wiremock and spring-cloud-contract-stub-runner dependencies:


3.2. Consumer Side Setup

Now it’s time to configure our stub runner, which will inform our consumer of the available stubs in our local Maven repository:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
  workOffline = true,
  ids = "com.baeldung.spring.cloud:spring-cloud-contract-producer:+:stubs:8090")
public class BasicMathControllerIntegrationTest {

    private MockMvc mockMvc;

    public void given_WhenPassEvenNumberInQueryParam_ThenReturnEven()
      throws Exception {

Note that the ids property of the @AutoConfigureStubRunner annotation specifies:

  • com.baeldung.spring.cloud — the groupId of our artifact
  • spring-cloud-contract-producer — the artifactId of the producer stub jar
  • 8090 — the port on which the generated stubs will run

4. When the Contract is Broken

If we make any changes on the producer side that directly impact the contract without updating the consumer side, this can result in contract failure.

For example, suppose we’re to change the EvenOddController request URI to /validate/change/prime-number on our producer side.

If we fail to inform our consumer of this change, the consumer will still send its request to the /validate/prime-number URI, and the consumer side test cases will throw org.springframework.web.client.HttpClientErrorException: 404 Not Found.

5. Summary

We’ve seen how Spring Cloud Contract can help us maintain contracts between a service consumer and producer so that we can push out new code without any worry of breaking the contracts.

And, as always, the full implementation of this tutorial can be found over on GitHub.

I just announced the new Spring 5 modules in REST With Spring:


Leave a Reply

2 Comments on "An Intro to Spring Cloud Contract"

newest oldest most voted
Notify of
Ron Wheeler

How doe this relate to OpenAPI (Swagger)?

Loredana Crusoveanu

OpenAPI is meant for generating documentation for an API. CDCs also rely on API documentation but in the form of “contracts” between the consumers of the API and the producer. This is helpful to ensure that changes to the API don’t break the functionality for existing clients.