[Spring Boot] Consumer Driven Tests using Spring Cloud Contract with WebFlux

Jay Kim
2 min readOct 14, 2021

There are numerous cases where a service needs to make use of the APIs from other services.

On the provider side, it might be sufficient to write unit tests to verify that the endpoints provide the data with appropriate fields and data types. However on the consuming side, using test doubles to mimic the provided API might lead to false positive results because the tests are based on the assumption.

This led to an opportunity to learn about Spring Cloud Contract. This example covers how Spring Cloud Contract is applied to a WebFlux application.

Provider (Server)


In order to use Spring Cloud Contract, spring-cloud-starter-contract-verifier needs to be added and spring-web-test-client is used because this example covers integration with WebFlux.

Also, a maven plugin needs to be added like below. This plugin will generate a test class called ContractVerifierTest.java under target/generated-test-sources/contracts/<package> based on a provided contract (Contract DSL can be written in Groovy, Java, YML, Kotlin).

It can be noticed that under configuration, there is baseClassForTests property mapped to ContractTestSetup.java. This base class stubs the return value of the repository and sets up RestAssured for WebFlux.

Defining Contracts

This server application provides User information through an endpoint GET /users/{id}. User has a few properties like below:

A sample JSON of user is captured in /test/resources/contracts/userResponse.json.

This JSON file can be used when writing contracts. There are many ways of asserting the body. For this example, only the data type of each JSON field will be asserted.

With this much information, running mvn test will generate ContractVerifierTest.java and run this test automatically. Let us examine what this generated class looks like.

It can be observed that this generated test class extends the base test class implemented during setup (ContractTestSetup.java). Also, based on the userResponse.yml, it checks if each of the property has a data type we defined inside the JSON file.

Provider side is done. Let us see how we can continue on the consumer side.

Consumer (Client)


With the contract written on the provider side, running mvn package creates a jar <artifactId>-<version>-stubs.jar under target directory. This means that the stubs.jar can be installed locally or on a server and the client application can use it during testing.

Therefore, stubs.jar and spring-cloud-starter-contract-stub-runner need to be added to pom.xml.

Writing Tests

On the consumer side, test cases can be written assuming that the server will return the JSON data defined in userResponse.json (on the provider side).

Full source can be found at :