Skip to content
javahacks.dev
Testing

How to Do Contract Testing With Spring Cloud Contract

Do contract testing with Spring Cloud Contract: write Groovy or YAML contracts on the producer, generated tests, stubs for consumers and publishing in CI.

5 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Spring, JUnit5, GitHub Actions, Selenium and Jenkins logos.

When one service calls another over HTTP, each team tests its own side against a guess about the other. The producer changes a field name, its own tests pass, and the consumer breaks in staging. Contract testing replaces the guess with a shared, executable description of the interaction. Spring Cloud Contract takes the producer-driven approach: the producer owns the contracts, the build verifies the producer against them, and the same build publishes stubs that consumers test against. This post sets up the whole loop on Spring Boot 4 with JUnit 5, for an HTTP interaction, and compares it with Pact.

Producer: write a contract

A contract is a file in the producer repository, under src/test/resources/contracts/. YAML is the format with the least ceremony:

src/test/resources/contracts/orders/get_order.ymlYAML
description: should return an existing order
request:
  method: GET
  url: /orders/42
response:
  status: 200
  headers:
    Content-Type: application/json
  body:
    id: 42
    status: "PLACED"
    total: 19.90
  matchers:
    body:
      - path: $.total
        type: by_regex
        value: "[0-9]+\\.[0-9]{2}"

The request says what a consumer sends, and the response says what the producer promises. The matchers section loosens exact values into patterns for the generated test and for the stub: the producer test accepts any matching total, while the stub returns the literal example. Without matchers, the generated test would require exactly 19.90, and the contract would double as a fixture. Keep contracts to what consumers rely on: a field that no consumer reads should not be in the contract, since adding it later would then count as a break only for those who read it.

Groovy DSL contracts are also supported and allow more logic. Choose YAML for simple cases and Groovy when you need dynamic values or request bodies built from parts.

Producer: base class and plugin

The plugin turns each contract into a JUnit test. The test needs a base class that sets up the application and its dependencies:

src/test/java/com/example/orders/ContractBase.javajava
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
abstract class ContractBase {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService orders;

    @BeforeEach
    void setUp() {
        RestAssuredMockMvc.mockMvc(mvc);
        when(orders.find(42L)).thenReturn(new Order(42L, "PLACED", new BigDecimal("19.90")));
    }
}
pom.xmlXML
<plugin>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-contract-maven-plugin</artifactId>
  <extensions>true</extensions>
  <configuration>
    <testFramework>JUNIT5</testFramework>
    <baseClassForTests>com.example.orders.ContractBase</baseClassForTests>
  </configuration>
</plugin>

On mvn verify the plugin generates a test class per contract directory, each extending the base class, which sends the request and asserts on the response using the contract. A producer that changes status to state fails its own build, with the contract name in the failure. The base class decides how deep the check goes: with the controller and a mocked service, as here, the test covers serialisation and routing but not the database. That is usually the right depth, and it runs in the unit-test phase. Use a @MockitoBean, as described in replacing beans in Spring tests, for the collaborators. Several base classes can be mapped to contract directories when different contracts need different setup.

Producer: publish stubs

The same plugin packages the contracts as a stubs jar, with a WireMock mapping per contract, and installs or deploys it alongside the main artifact with the classifier stubs. Publish it to your artifact repository in CI as part of the normal release. Consumers fetch com.example:orders:1.4.0:stubs, and a build that fails on the producer side never publishes a stub, so consumers only see stubs that the producer has verified. That ordering is the guarantee.

Consumer: test against stubs

The consumer adds the Stub Runner and declares which producer stubs to run:

java
@SpringBootTest
@AutoConfigureStubRunner(
    ids = "com.example:orders:+:stubs:8090",
    stubsMode = StubRunnerProperties.StubsMode.REMOTE,
    repositoryRoot = "https://repo.example.com/maven")
class OrderClientTest {

    @Autowired OrderClient client;

    @Test
    void reads_an_order() {
        Order order = client.find(42L);
        assertEquals("PLACED", order.status());
    }
}

The Stub Runner downloads the stubs jar, starts a WireMock server on port 8090 serving the recorded responses, and the client under test is configured to call localhost:8090. The + takes the latest version, which suits development; pin a version, or use the version the consumer is deployed against, in a release pipeline. StubsMode.LOCAL reads from ~/.m2, which is convenient on a laptop. The consumer test then verifies that the consumer can deal with exactly what the producer promised, with no running producer needed, and in the time of a unit test. The WireMock documentation at wiremock.org covers the server underneath.

Messaging

Contracts also describe messages: an input that triggers a method and an output sent to a destination, for Kafka, RabbitMQ and others, with the same generated tests and stubs. The plugin cannot know your message payload rules unless you write them in the contract, so treat it the same way as HTTP.

Compared with Pact

Pact is consumer-driven: the consumer writes the expectations it relies on, publishes them to a broker, and the provider verifies against them. Spring Cloud Contract is producer-driven: the producer decides what it offers, and consumers test against it. The trade-offs follow from that. Producer-driven suits an organisation where the owner of the API leads its design and wants a single place to say what it supports; it is simpler in a Spring estate. Consumer-driven shows which consumers use which fields, so a producer can see that a field is unused and safe to remove, and it works across languages. See contract testing with Pact for the other approach. Pick one per boundary; running both on the same API doubles the maintenance.

Practices

Keep contracts few and about behaviour that matters across the boundary: status codes, required fields, error shapes. They are not a replacement for the producer's own tests, and they should not repeat business rules. Version contracts with the API, and when a break is intended, see how to release it in API versioning strategies. Review contract changes as API changes, with the consumers' owners in the review. Run the producer verification in CI on every pull request, so an incompatible change is found before merge, not after a consumer deploy.

Where it sits in the test strategy

Contract tests replace the end-to-end test whose only job was to check that two services still understand each other. They are cheap and run without environments, so they belong low in the pyramid, and they let you cut the number of slow integration tests, a point made in the test pyramid for Java services. They do not test behaviour behind the API, performance or deployment wiring. Use test slices to keep the producer side fast.

When this does not apply

If the consumer is not JVM-based, the stubs still work as a WireMock server, but the tooling is less pleasant, and Pact has better cross-language support. For public APIs with unknown consumers, publish an OpenAPI description and run compatibility checks on it instead. The reference is the Spring Cloud Contract documentation.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.