• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Contact Us

All about code

  • Java
    • Spring
      • Spring Boot
      • Spring Cloud
    • Java Miscellaneous Tips
    • Java Design Patterns
  • Data Structures and Algorithms
    • Algorithms
    • Data Structures
  • Thoughts and Stories
  • AI

Spring Cloud Contract: How to Implement Contract Tests

penmanship pen signature document 2561217

Introduction

We have already seen how to use Pact to perform contract testing in a previous article. Spring Cloud provides its solution with Spring Cloud Contract. In this article, we will see how to implement a test using this tool for a couple of simple REST-based micro-services.

A Few Words on Spring Cloud Contract

Spring Cloud Contract supports the implementation of contract tests for JVM-based applications. It includes three main components:

  • Spring Cloud Verifier
  • Spring Cloud Stub Runner
  • Spring Cloud WireMock

It defines the contracts using a Groovy DSL syntax. These definition files generate JSON stubs that are then included in a jar and deployed in a Maven repository. Differently from Pact, the contract creation is started on the producer side.

Spring Cloud Contract Configuration on the Producer

. The first thing to do in the producer application is to set the spring-cloud-starter-contract-verifier dependency:

		<dependency>
		    <groupId>org.springframework.cloud</groupId>
		    <artifactId>spring-cloud-starter-contract-verifier</artifactId>
		    <scope>test</scope>
		</dependency>

We also need a plugin to generate the stubs from the definitions and tests extending a base class:

			<plugin>
			    <groupId>org.springframework.cloud</groupId>
			    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
			    <version>4.1.3</version>
			    <extensions>true</extensions>
			    <configuration>
			        <baseClassForTests>
			            com.codingstrain.springcloud.sample.libraryapp.authors.BaseTestClass
			        </baseClassForTests>
			    </configuration>
			</plugin>

In the /test/resources folder of our project, we include a Groovy definition file we call testProducer.groovy in our example. It will contain the following:

import org.springframework.cloud.contract.spec.Contract

Contract.make {
    description "return biography info for an author named Goethe"
    request {
        method GET()
        url("/authors/findAuthor") {
            queryParameters {
                parameter("name", "Goethe")
            }
        }
    }
    response {
        body("{\"name\":\"Goethe\",\"biography\":\"Bio info\"}")
        status 200
    }
}

The base class will be:

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

    @Autowired
    private AuthorController authorController;

    @BeforeEach
    public void setup() {
        StandaloneMockMvcBuilder standaloneMockMvcBuilder 
            = MockMvcBuilders.standaloneSetup(authorController);
        RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);
    }
}

If we run Maven install a jar will be generated and installed in the local Maven repository with the JSON stub. Furthermore, a test will be generated that extends the base class and follows the Groovy definition file configuration.

Spring Cloud Contract Configuration on the Consumer

On the consumer side, we set the following dependencies:

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-contract-wiremock</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-contract-stub-runner</artifactId>
			<scope>test</scope>
		</dependency>

We then create a test class like this:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@AutoConfigureJsonTesters
@AutoConfigureStubRunner(
  stubsMode = StubRunnerProperties.StubsMode.LOCAL,
    ids = "springcloud.sample:springcloud.sample.libraryapp.testing.contract.authors:+:stubs:8091")
public class ConsumerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testConsumer()
      throws Exception {
 
        mockMvc.perform(MockMvcRequestBuilders.get("/library/findAuthor?name=Goethe")
          .contentType(MediaType.APPLICATION_JSON))
          .andExpect(status().isOk())
            .andExpect(content().string("{\"name\":\"Goethe\",\"biography\":\"Bio info\"}"));
    }
}

The test above uses the stub in the local maven repository to perform the test.

Conclusion

Spring Cloud Contract is a valuable alternative to Pact. We have seen how a contract stub can be generated as a jar and installed in the local Maven repository and how tests can be performed on the producer and consumer side. You can find the source code of the example of this article on GitHub.

Primary Sidebar

Social

  • Facebook
  • LinkedIn
  • Twitter

Archives

  • May 2026
  • April 2026
  • March 2026
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • September 2023
  • May 2023
  • March 2023
  • January 2023
  • November 2022
  • September 2022
  • August 2022

Recent Posts

  • Better Avoid Spring Boot Lazy-initialization @PostConstruct Trap
  • How To Handle Large Datasets in Spring Boot
  • How to Log HTTP Incoming Requests in Spring Boot
  • How to Reliably Implement Post-Commit Actions in Spring
  • Brief and Easy Explanation of HATEOAS

TAGS

Algorithms Apache POI Backtracking Date Structures Dynamic Programming engineering Graphs Greedy Horror Stories HSSF Java Java New Features Java Principles Java tips real life Sorting Spring Boot Spring Cloud Strings Trees

Footer

Privacy Policy Cookie Policy Terms and Conditions