Skip to content

    System Design

    Contract Testing with Pact and Spring Cloud Contract

    Learn how contract tests catch breaking API changes before deploy: Pact files, provider verification and states, and Spring Cloud Contract stubs.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: The Testing Pyramid for Backend Systems, OpenAPI, Contract-First Design and API Contracts

    What you'll learn: By the end of this lesson you will be able to explain what a contract test checks that a unit test and an end-to-end test do not, describe the Pact flow (consumer test, pact file, provider verification, provider states), contrast it with the provider-owned flow of Spring Cloud Contract (contracts, generated tests, stubs, Stub Runner), keep contracts loose enough not to break on harmless changes, and run a real Pact consumer and provider verification in a Spring lab, with no broker and no Docker.

    Think of a recipe card pinned in a shared kitchen. The baker who uses the card does not need the whole supplier's catalogue; she needs "flour, 1 kg, a number on the label". If the supplier changes the label from kilograms to pounds, she finds out only when a cake fails. A contract test is the habit of checking the label every time the supplier prints a new one, using only the lines the baker actually reads.

    Two services have the same problem. A checkout service calls a catalogue service; each team tests its own code and everything is green, yet a field rename breaks checkout in production. OpenAPI, contract-first and API contracts is where the description of an API lives; this lesson is about proving, per consumer, that the description still holds. Front-end teams meet the same idea from the other side in Contract testing for front ends.

    Verified with Pact JVM 4.7.7, Spring Boot 4.1.2 and Java 25, and the Pact and Spring Cloud Contract documentation, on 2026-12-02.

    The core idea

    A contract test checks the agreement between two services, in isolation from each other: the consumer records what it needs, the provider proves it still delivers at least that. Neither test starts the other service. The contract is the artifact that travels between the two test suites.

    Three illustrations run through the lesson:

    • Minimal example: the lab, a catalogue endpoint and a checkout client with a real Pact flow.
    • Realistic example: ShopStream's checkout and catalogue teams, in "In practice".
    • Failure example: a provider renames priceCents to price; its own tests pass and the pact fails.

    What a contract is, and who owns it

    A contract is a precise statement of one interaction: this request, and a response with at least these parts. The two tools in this lesson differ mainly in who writes it.

    Pact Spring Cloud Contract
    Who writes the contract The consumer, as a test Usually the provider team, in its repository (a consumer can propose one)
    Contract format A pact file (JSON), generated from the consumer's test A contract DSL file: Groovy, YAML, Java or Kotlin
    What proves the provider Provider verification replays the pact against the real provider Tests generated from the contracts run against the provider
    What the consumer tests against Pact's mock provider, built from the same interaction Stubs produced from the contracts, started by Stub Runner

    "Consumer-driven" means the consumer's needs shape the contract. Pact's documentation says consumer tests should only make "assertions about things that will affect the consumer if they change" and suggests the question: if the answer is none, do not include it.

    The Pact flow: one pact file between two test suitesConsumer test to Mock provider (real request); Consumer test to Pact file (writes); Pact file to Provider verification (replays); Provider verification to Real provider (each interaction)Consumer test: checkout-serviceConsumer testcheckout-serviceMock provider: from the testMock providerfrom the testPact file: JSON, versionedPact fileJSON, versionedProvider verification: catalog-serviceProviderverificationcatalog-serviceReal provider: in the test JVMReal providerin the test JVMreal requestwritesreplayseach interaction

    Figure 1. The Pact flow. How to read this: the consumer test talks to a mock provider; when it passes, Pact writes the pact file. Provider verification reads the same file and replays every recorded request against the real provider, so the two services never run together.

    The Pact flow, step by step

    The Pact documentation describes the flow in four moves. Each interaction is exercised by a unit test in the consumer's codebase; Pact starts a mock provider that compares the real request with the expected one and answers with the expected response; after the tests pass a pact file records every interaction; and provider verification replays each request against the real provider, which passes "if each request generates a response that contains at least the data described".

    "At least" is the important phrase. The provider may add fields, reorder them or serve other consumers; verification fails only when it stops providing something a consumer declared.

    sequenceDiagram accTitle: Pact consumer test and provider verification accDescr: The consumer test calls a Pact mock provider and writes a pact file. Later the provider verification reads the pact, sets up the provider state, replays the request against the real provider and compares the response. participant C as Consumer test participant M as Pact mock provider participant F as Pact file participant V as Provider verification participant P as Real provider C->>M: GET /products/p-100 M-->>C: 200 with id and priceCents C->>F: write the interaction V->>F: read the interaction V->>P: set up state "product p-100 exists" V->>P: GET /products/p-100 P-->>V: 200 with id, name, priceCents, currency V->>V: contains at least id and priceCents? pass

    Figure 2. One interaction through both halves. How to read this: the top half runs in the consumer's build, the bottom half in the provider's build, possibly days later. The provider's response may carry more fields than the pact lists.

    Provider states

    An interaction often depends on data: "p-100 exists". Pact calls that precondition a provider state. The consumer names it with given(...); the provider test has a method annotated with @State and the same name that puts the data in place. The documentation says each interaction is verified in isolation, "with no context maintained from the previous interactions", and that a state describes the provider's condition, not the consumer's.

    Matching: be strict about requests, loose about responses

    Pact's matching guide puts it plainly: be strict with what you send and "as loose as possible" with the response. A type matcher says "an integer is here" without fixing its value; a regular expression fixes a format. Random values in a pact are discouraged because with a broker they make the contract look changed when it is not. A consumer that lists every field of a response couples itself to fields it never reads.

    Spring Cloud Contract: the provider-owned flow

    Spring Cloud Contract starts from the provider. Its documentation describes a contract as "an agreement on how the API or message communication should look" and lists these purposes: make sure the stubs used when developing a client do what the real server does, and generate the boilerplate test code for the server side. The contract is a DSL file in Groovy, YAML, Java or Kotlin, with a request and a response block.

    In the documented consumer-driven flow, the consumer writes the contract in a clone of the producer's repository and "the producer owns the contracts", which live in the producer's repository. A Gradle or Maven plugin generates tests from the contracts and produces and installs a stubs jar; the first generated test fails until the producer implements the feature, which is the test-driven loop. The consumer then uses Stub Runner (@AutoConfigureStubRunner) to download and run those stubs. The overview also warns that contracts must come from a trusted source: do not download or interact with contracts from untrusted locations.

    The Spring Cloud Contract flow: contracts in the provider's repositoryContract DSL to Generated tests (generates); Contract DSL to Stubs jar (produces); Stubs jar to Stub Runner (downloads); Stub Runner to Consumer code (serves stubs)Contract DSL: provider repoContract DSLprovider repoGenerated tests: run on providerGeneratedtestsrun on providerStubs jar: published artifactStubs jarpublishedartifactStub Runner: consumer testStub Runnerconsumer testConsumer code: checkoutConsumer codecheckoutgeneratesproducesdownloadsserves stubs

    Figure 3. The Spring Cloud Contract flow. How to read this: one contract feeds two outputs. The generated tests keep the provider honest; the stubs let the consumer test against something the provider's build has verified.

    The lab in this lesson does not run Spring Cloud Contract. Its Gradle plugin and Stub Runner were not added to the course's shared build, so everything said about it here comes from the documentation, not from a run.

    Where contract tests sit

    Test What it proves What it cannot prove
    Unit test One class behaves That another service agrees
    OpenAPI check The provider matches its published description That a particular consumer's usage is covered
    Contract test Each consumer's declared needs still hold Business correctness, performance, anything outside the declared interaction
    End-to-end test A real flow works with real services Which side broke, quickly and cheaply

    The OpenAPI lesson, OpenAPI, contract-first and API contracts, covers the provider-wide description; a consumer-driven contract is narrower and per consumer. They complement each other: the description says what the provider offers, the pact says what is in use. The place of all of these in a full suite is the job of the testing pyramid lesson for the back end, which is written separately.

    flowchart TD accTitle: Choosing a contract approach accDescr: A decision flow. If the provider team can see and verify every consumer, a provider-owned contract such as Spring Cloud Contract fits. If consumers are many and independent, consumer-driven pacts fit. If neither side can run the other, use a published OpenAPI description plus a diff check. A[Who needs to change the contract?] --> B{Provider team controls and knows its consumers?} B -- yes --> C[Provider-owned contracts: Spring Cloud Contract] B -- no --> D{Consumers can write tests against a mock?} D -- yes --> E[Consumer-driven pacts: Pact] D -- no --> F[Published OpenAPI description plus diff check]

    Figure 4. A starting point for the choice, not a rule. How to read this: follow the questions from the top. Both tools can work for either team shape; the diagram shows which is the more natural fit.

    Build it: a real Pact flow in a Spring lab

    This is the minimal example. The lab is examples/spring-labs/labs/contract-testing-pact/. It uses the real Pact JVM libraries (au.com.dius.pact.consumer:junit5 and au.com.dius.pact.provider:junit5, 4.7.7), which run inside the test JVM. There is no Pact Broker, no Docker and no network call. The provider is a real Spring MVC controller started on a local port by the embedded servlet container; the catalogue is an in-memory map.

    Goal. See a consumer test produce a pact, a provider verification pass against it, and the same verification fail after a harmless-looking rename.

    Setup. From examples/spring-labs:

    ./gradlew :labs:contract-testing-pact:test

    How it works. The consumer, CatalogClient, reads two fields of the product response:

    JsonNode body = json.readTree(response.body());
    if (!body.path("priceCents").isInt()) {
        throw new IOException("priceCents missing or not an integer");
    }
    return Optional.of(new Price(body.path("id").asText(), body.path("priceCents").asInt()));

    Its pact names exactly those two fields and matches them by type, not by value:

    .body(new PactDslJsonBody().stringType("id", "p-100").integerType("priceCents", 249))

    The provider test replays the pact against the real controller, with @State methods that put p-100 in the in-memory map or clear it. A second provider, DriftedProviderApp, serves price as a decimal string instead of priceCents. The three Pact test classes are launched by one ContractFlow helper, through the JUnit Platform Launcher, because the consumer must run first and the drifted run is meant to fail.

    Expected output, captured from a real run (Pact JVM 4.7.7, Spring Boot 4.1.2, compiled with --release 25):

    # Pact JVM 4.7.7, run in-process: no broker, no Docker, no network.
    consumer: checkout-service  provider: catalog-service  pact specification: 3.0.0
    interaction 1: a request for product p-100
      provider state: product p-100 exists
      request:  GET /products/p-100
      response: 200, body fields: id, priceCents
    interaction 2: a request for product p-999
      provider state: product p-999 does not exist
      request:  GET /products/p-999
      response: 404
    
    consumer tests (Pact mock provider):       2 passed, 0 failed
    verification, current provider:             2 passed, 0 failed
    verification, provider after the rename:    1 passed, 1 failed

    What to notice. The pact has two interactions and names only id and priceCents. The current provider passes both. The drifted provider fails the interaction that reads a product; the 404 interaction still passes. No test in the provider's own code needed to change for the failure to show up, because the pact came from the consumer.

    Choosing between them

    Concern Pact Spring Cloud Contract
    Language reach Many languages share one pact format Strongest on the JVM and Spring
    Who must act when a contract changes The provider verifies the new pact The provider owns the contract file, so a change is a provider commit
    Works well when Many independent consumers, possibly in other languages Few consumers the provider team can see, one build tool chain
    Typical cost Sharing pacts (a broker or a shared folder) and keeping consumer tests loose Publishing and versioning stubs; contracts reviewed by the provider team

    In practice: ShopStream's checkout and catalogue

    This is the realistic example, an educational scenario on the course's running example ShopStream. Every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's checkout team and catalogue team deploy independently. The catalogue team plans to rename priceCents to a structured price object. Their unit tests and their OpenAPI check pass. Two other consumers, the mobile app and the search indexer, read different fields of the same endpoint.

    Starting architecture

    ShopStream: three consumers of one catalogue endpointCheckout to Catalogue service (GET); Mobile BFF to Catalogue service; Search indexer to Catalogue serviceCheckout: reads priceCentsCheckoutreads priceCentsMobile BFF: reads nameMobile BFFreads nameSearch indexer: reads all fieldsSearch indexerreads all fieldsCatalogue service: GET /products/idCatalogueserviceGET /products/idGET

    Figure 5. Three consumers, three different slices of one response. How to read this: each arrow is a separate consumer with its own needs, so a change that is safe for two can break the third.

    Options considered

    Option Catches the rename before deploy Cost
    A. Rely on end-to-end tests Late, and does not say which side broke Slow, flaky, shared environment
    B. Pact per consumer, verified in the provider's build Yes, naming the consumer Consumers write and maintain loose tests
    C. Provider-owned contracts Yes, if all consumers are known The provider team writes every contract

    The decision

    Option B for checkout and mobile, whose teams can write consumer tests; the search indexer, owned by the same team as the catalogue, stays on the provider's own tests. Each pact lists only the fields its consumer reads.

    Rollout and verification

    Pacts are verified in the catalogue's build on every change. Pact's can-i-deploy command, which needs a Pact Broker that stores verification results per version and environment, would then gate each deploy: exit code 0 means the version has a successful verification with the versions already running there. The lab does not run a broker, so the gate is only described here. Verification is "every consumer's latest pact passes against the provider's current build".

    The 2 a.m. failure

    Checkout starts rejecting orders after a catalogue deploy: priceCents missing. The catalogue release had passed its own tests because nobody had added the checkout pact to its verification. The check: list which consumers' pacts the provider build verified; one was missing. The mitigation is to roll back the catalogue. The lasting fix is a provider build that fails when any consumer with a registered pact is not verified, and a rule that a field is deprecated in two steps: add the new field, wait for the pacts to move, then remove the old one.

    Architect's notes

    • Contracts are per consumer. A provider-wide description does not say which fields are actually used.
    • Keep consumer tests loose. Type matchers and only the fields the consumer reads; random data makes a pact look changed.
    • A contract is not a functional test. Business rules belong in the provider's own tests.
    • Version and share pacts deliberately. Without a broker or a shared folder the provider cannot verify what it cannot find.
    • Trust the source. Spring Cloud Contract documentation says contracts must come from a trusted source.
    • Say what you did not run. This lesson's lab runs Pact; it does not run Spring Cloud Contract or a broker.

    Common mistakes

    • Putting every field in the pact. The consumer then fails on changes it never cared about.
    • Using contract tests as end-to-end tests. They check an interaction, not a flow.
    • Verifying only the latest pact. A consumer still deployed in production may be on an older one.
    • Provider states that do too much. A state describes the provider's condition, not the whole scenario.
    • Skipping the failure case. The 404, 409 and validation errors are part of what a consumer relies on.
    • Treating a green pact as a guarantee of behaviour. It proves shape and status for the listed interactions.

    Key takeaways

    • A contract test proves the agreement between two services without running them together.
    • In Pact the consumer writes the contract as a test; the provider verifies it, and passes when its response contains at least what the pact lists.
    • Provider states set up the data an interaction needs; matching should be strict on requests and loose on responses.
    • Spring Cloud Contract is provider-owned: contracts generate provider tests and stubs, which Stub Runner serves to consumers.
    • The lab ran real Pact JVM offline; Spring Cloud Contract and a broker are described from documentation only.

    Practice exercises

    Exercise 1 (20 min). Run the lab. In DriftedProviderApp, find the one change that fails the pact, and say why the 404 interaction still passes.

    Exercise 2 (45 min). Add a third interaction to the consumer test for a request with a malformed id that returns 400 with an error body. Decide which fields the consumer really needs and which it should leave out.

    Exercise 3 (1 hour). Change integerType to an exact value of 249 in the pact, change the provider's data and re-run. Explain what tightening a response matcher costs. Restore the code and re-run.

    Exercise 4 (2 hours). For ShopStream's three consumers, write which fields each one reads, whether each should use a pact or a provider-owned contract, and how the catalogue would deprecate priceCents.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments