Skip to main content

Consumer-Driven Contract Testing in Spring Boot 4.2: Spring Cloud Contract vs Pact (and Stubborn Contract)

Producer and consumer builds on Spring Boot 4.2, run for real with Spring Cloud Contract 5.0.3, Stubborn Contract 0.2.4 and Pact JVM 4.7.7: stubs, pact files, CI order, and four producer changes compared across both tools. Includes the Boot 4.2 REST Assured trap and the news that Spring Cloud Contract has left the Spring Cloud release train.

Two Spring Boot services agree on a JSON shape. The orders service returns total, the checkout service reads total. On Friday someone on the orders team renames it to totalAmount because the new name is clearer. Every unit test on the orders side stays green, because they test the new name. Every unit test on the checkout side stays green, because they mock the old name. The first place the two disagree is production, where checkout starts charging customers a null amount. Consumer-driven contract testing closes that gap without standing up both services together. A contract describes one conversation (a request and the response the consumer needs back). The consumer proves its client works against the contract, the producer proves its service still honours it, and a break shows up as a red build on the side that caused it. This post builds one orders producer and one checkout consumer on Spring Boot 4.2, wires them up with Spring Cloud Contract and with Pact, breaks the producer four different ways, and shows what each tool says. Every build and failure quoted below was run for this post, and the output is committed.
Verified versions (run on 29 November 2026). Temurin JDK 25.0.5.1 (LTS), Spring Boot 4.2.0 (GA 19 November 2026), Spring Cloud Contract 5.0.3 (latest on Maven Central), Stubborn Contract 0.2.4 (latest), Pact JVM 4.7.7 (latest), REST Assured 7.0.0, WireMock 3.13.2, Groovy 5.1.3 (managed by Boot 4.2), Maven 3.9.11. Versions were read from maven-metadata.xml and from the resolved dependency trees in 01-versions.txt.

Two things changed since older tutorials. First, Spring Cloud Contract has left the Spring Cloud release train: the 2026.0.0 BOM no longer manages it, and development continues as Stubborn Contract (see the section on that below). Second, Spring Cloud Contract 5.0.3 does not work on Spring Boot 4.2 out of the box: its generated tests crash inside REST Assured until you override one version.
The companion code is the contracts module of asmhatre/java-testing-lab. The deeper material (full generated tests, complete failure output, the migration mapping) is folded into collapsible sections inside this page, so you can read straight through or open what you need.

A contract is a promise about one conversation, checked from both ends

Think of the contract as a small, executable agreement: when you send GET /orders/42, I answer 200 with an object containing an id, a status and a numeric total. Nothing more. It is not an OpenAPI document describing everything the service can do; it describes what one consumer relies on. The agreement is checked twice, in two different builds. The consumer side runs the real client code against a fake server that answers exactly as the contract says, which proves the client can cope with that answer. The producer side takes the same contract, sends the request to the real service, and compares the real answer, which proves the service still says what it promised. Neither build needs the other service running.
checkout-consumercalls GET /orders/42orders-producerserves GET /orders/42the contractGET /orders/42 → 200{ id, status, total }check 1: client works with itcheck 2: service still honours itNo shared environment and no network between the two services: each check runs inside its own build.A break shows up as a red build on the side that made the change.
The diagram shows the property that matters: the two checks are independent builds linked only by the contract. That is why this is cheaper and less flaky than an end-to-end environment, and why a break points at the team that changed something. What the two tools disagree on is who writes the contract and how much of the response it pins down. The rest of the post is that difference, demonstrated.

What contract tests do not replace

A contract test says nothing about whether the producer’s behaviour is correct, whether the database is wired, or whether the gateway forwards the header. Keep your producer tests. Contract tests only cover the seam between two services.

The two services we are going to test

The producer is a small orders API with two endpoints: GET /orders/{id} and POST /orders. The consumer is a checkout service with a RestClient wrapper. The consumer deliberately models only three fields, even though the producer sends five, because that gap is what makes the two tools behave differently later. Here is the consumer’s whole view of an order (file: Order.java):
public record Order(long id, String status, BigDecimal total) {}
And the producer’s controller (file: OrderController.java):
@RestController
public class OrderController {

    public record CreateOrder(List<Order.Line> items) {}

    private final OrderRepository repository;
    private final String variant;

    OrderController(OrderRepository repository, @Value("${orders.variant:baseline}") String variant) {
        this.repository = repository;
        this.variant = variant;
    }

    @GetMapping("/orders/{id}")
    ResponseEntity<Map<String, Object>> get(@PathVariable long id) {
        return repository.find(id)
                .map(o -> ResponseEntity.ok(OrderRepresentation.of(o, variant)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "ORDER_NOT_FOUND")));
    }

    @PostMapping("/orders")
    ResponseEntity<Map<String, Object>> create(@RequestBody CreateOrder request) {
        Order order = repository.create(request.items());
        return ResponseEntity.status(HttpStatus.CREATED).body(OrderRepresentation.of(order, variant));
    }
}
The JSON itself is built in OrderRepresentation.java, which reads an orders.variant property. That property exists only so this lab can simulate a producer change on demand (ORDERS_VARIANT=rename-total and so on). A real service would just contain the change.
Why the consumer ignores two fields. Jackson 3, the default in Spring Boot 4, does not fail on unknown properties, so Order happily reads the five-field response into three fields. This is the realistic situation: a consumer almost never uses everything a producer sends.

Spring Cloud Contract: the producer writes the contract and the consumer gets a stub

With Spring Cloud Contract the contract lives in the producer’s repository, as a file under src/test/resources/contracts. The build does two things with it: it generates a JUnit test that fires the request at the real service and asserts the response, and it generates WireMock stubs that it packages into a -stubs.jar for consumers. Here is the contract for fetching an order (file: shouldReturnOrder.yml). YAML is only one of the formats; the Groovy and Java DSLs work too.
description: a confirmed order is returned by id
name: shouldReturnOrder
request:
  method: GET
  url: /orders/42
response:
  status: 200
  headers:
    Content-Type: application/json
  body:
    id: 42
    status: "CONFIRMED"
    total: 129.90
    currency: "INR"
    items:
      - sku: "BOOK-1"
        qty: 2
The generated tests extend a base class you write, which is where the producer puts itself into the state the contract assumes (order 42 exists, the next new id is 1001). It is also where the choice of test mode lives (file: ContractVerifierBase.java):
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class ContractVerifierBase {

    @LocalServerPort
    int port;

    @Autowired
    OrderRepository repository;

    @BeforeEach
    void setUp() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = port;
        repository.reset();
    }
}
The plugin is configured in the producer’s POM (file: pom.xml). Note EXPLICIT mode, which I come back to in a callout:
      <plugin>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-contract-maven-plugin</artifactId>
        <version>${scc.version}</version>
        <extensions>true</extensions>
        <configuration>
          <testFramework>JUNIT5</testFramework>
          <testMode>EXPLICIT</testMode>
          <baseClassForTests>com.ankurm.contracts.orders.ContractVerifierBase</baseClassForTests>
        </configuration>
      </plugin>
Running mvn clean install generates the test class, runs it against the real service on a random port, and builds the stubs jar. The relevant lines from the committed transcript (04-producer-baseline.txt):
[INFO] Running com.ankurm.contracts.orders.OrdersTest

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
contract YAMLsrc/test/resourcesgenerated JUnit testruns vs real servicestubs jarWireMock mappingsconsumer testruns vs WireMock stubsmvn installWritten by: the producer team (consumers send pull requests or ask for changes).Producer proof: the generated test fails when the service stops matching the YAML.Consumer proof: only as fresh as the stubs jar the consumer resolves (+ means latest).Lesson from the runs below: a contract change that is green on the producer can still be red on the consumer.
The diagram shows who owns what. Everything on the left is written by the producer team; the consumer only ever sees the stubs jar on the right. That is convenient for the consumer, and it is also the weakness: the consumer’s confidence is exactly as current as the stubs jar it resolves. The consumer test points the stub runner at that jar. With stubsMode = LOCAL it looks in ~/.m2, and the + in the id means latest version. It starts WireMock on port 8090 serving what the producer’s contracts describe (file: OrdersStubConsumerTest.java):
@SpringBootTest(properties = "orders.base-url=http://localhost:8090")
@AutoConfigureStubRunner(
        ids = "com.ankurm.contracts:orders-producer:+:stubs:8090",
        stubsMode = StubRunnerProperties.StubsMode.LOCAL)
class OrdersStubConsumerTest {
[INFO] Running com.ankurm.contracts.checkout.OrdersStubConsumerTest

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersStubConsumerTest
The code above is an excerpt; the full run is in 08-consumer-stub-run.txt.
Going deeper: the generated test, the stubs jar and the WireMock mapping This is the test Spring Cloud Contract generated from the YAML above (excerpt of 05-generated-test.txt). It calls the real service through REST Assured and asserts every field the contract lists, including the array contents:
	public void validate_shouldReturnOrder() throws Exception {
		// given:
			RequestSpecification request = given();


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

					.get("/orders/42");

		// then:
			assertThat(response.statusCode()).isEqualTo(200);
			assertThat(response.header("Content-Type")).isEqualTo("application/json");


		// and:
			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
			assertThatJson(parsedJson).field("['id']").isEqualTo(42);
			assertThatJson(parsedJson).field("['status']").isEqualTo("CONFIRMED");
			assertThatJson(parsedJson).field("['total']").isEqualTo(129.9);
			assertThatJson(parsedJson).field("['currency']").isEqualTo("INR");
			assertThatJson(parsedJson).array("['items']").contains("['sku']").isEqualTo("BOOK-1");
			assertThatJson(parsedJson).array("['items']").contains("['qty']").isEqualTo(2);
	}
The stubs jar contains the contracts themselves and one WireMock mapping per contract (listing in 06-stubs-jar.txt). This is the mapping the consumer’s stub runner serves for GET /orders/42 (07-wiremock-mapping.json; the ids are random per run):
{
  "id" : "e82107a2-c24d-4c1b-83e5-76e63809afb2",
  "request" : {
    "urlPath" : "/orders/42",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "body" : "{\"id\":42,\"status\":\"CONFIRMED\",\"total\":129.9,\"currency\":\"INR\",\"items\":[{\"sku\":\"BOOK-1\",\"qty\":2}]}",
    "headers" : {
      "Content-Type" : "application/json"
    },
    "transformers" : [ "response-template", "spring-cloud-contract" ]
  },
  "uuid" : "e82107a2-c24d-4c1b-83e5-76e63809afb2"
}
Because the stub body is the contract’s body, it carries currency and items even though checkout never reads them. That is the heavy-handed side of producer-owned contracts: everything the producer lists becomes a promise.
Default test mode failed on the first run. Spring Cloud Contract generates MockMvc tests by default. With a base class that boots the full application on a random port (@SpringBootTest(webEnvironment = RANDOM_PORT)) the first run failed with You haven’t configured a MockMVC instance. Setting <testMode>EXPLICIT</testMode> makes the generated tests use plain REST Assured against the real port, which is what the base class above configures.

Pact: the consumer writes the contract and the producer proves it

Pact reverses the ownership. The contract is written by the consumer’s test, and the file it produces (the pact) is what the producer is verified against. Because the consumer writes it from the code that actually calls the producer, a pact contains only the fields the consumer reads, and it matches them by type rather than by value. This is the interaction for fetching order 42 (file: OrdersPactConsumerTest.java). decimalType("total", 129.90) means: the example value is 129.90, but any decimal number is acceptable:
    RequestResponsePact orderExists(PactDslWithProvider builder) {
        return builder
                .given("order 42 exists and is confirmed")
                .uponReceiving("a request for order 42")
                .path("/orders/42")
                .method("GET")
                .willRespondWith()
                .status(200)
                .headers(JSON)
                .body(LambdaDsl.newJsonBody(o -> o
                        .integerType("id", 42)
                        .stringType("status", "CONFIRMED")
                        .decimalType("total", 129.90)).build())
                .toPact();
The test that uses it runs the real OrderClient against Pact’s mock server:
    @PactTestFor(pactMethod = "orderExists")
    void readsAnExistingOrder(MockServer server) {
        OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());

        Order order = client.find(42).orElseThrow();
        assertThat(order.status()).isEqualTo("CONFIRMED");
        assertThat(order.total()).isEqualByComparingTo(new BigDecimal("129.90"));
    }
Running it passes (02-consumer-pact-run.txt) and writes target/pacts/checkout-consumer-orders-producer.json. The lab copies that file into the producer’s test resources; in a real pipeline you would publish it to a Pact Broker instead.
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersPactConsumerTest
consumer testagainst Pact mock serverpact file (JSON)only fields it readsprovider verificationreplays vs real servicecopy / brokerWritten by: the consumer team, from the tests it already needed.Producer proof: each recorded request is replayed and the real response is compared by type.The pact says nothing about fields the consumer does not read, so the producer stays free to change them.Lesson from the runs below: dropping an unused field passes Pact and fails Spring Cloud Contract.
Compare this with the previous diagram. The arrow now runs from consumer to producer: the producer team does not write anything, it only has to make the recorded requests keep working. The verification test (file: OrdersPactVerificationTest.java) is plain JUnit 5 plus an HTTP target, so no Spring-specific Pact module is needed. The @State methods put the producer’s data into the situation each interaction was recorded in:
@Provider("orders-producer")
@PactFolder("pacts")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(PactVerificationInvocationContextProvider.class)
class OrdersPactVerificationTest {

    @LocalServerPort
    int port;

    @Autowired
    OrderRepository repository;

    @BeforeEach
    void before(PactVerificationContext context) {
        context.setTarget(new HttpTestTarget("localhost", port));
    }

    @TestTemplate
    void verifyPact(PactVerificationContext context) {
        context.verifyInteraction();
    }

    @State("order 42 exists and is confirmed")
    void order42Exists() {
        repository.reset();
    }
    ...
Verification replays each interaction and prints a verdict per interaction (04-producer-baseline.txt):
Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given order 42 exists and is confirmed
  a request for order 42
    returns a response which
      has status code 200 (OK)
      has a matching body (OK)
Going deeper: the pact file the consumer wrote This is the whole file (03-pact-file.json). Look at the response for order 42: it lists id, status and total and nothing else, with matchingRules saying integer, type and decimal. currency and items do not appear because the consumer never reads them.
{
  "consumer": {
    "name": "checkout-consumer"
  },
  "interactions": [
    {
      "description": "a request for order 42",
      "providerStates": [
        {
          "name": "order 42 exists and is confirmed"
        }
      ],
      "request": {
        "method": "GET",
        "path": "/orders/42"
      },
      "response": {
        "body": {
          "id": 42,
          "status": "CONFIRMED",
          "total": 129.9
        },
        "headers": {
          "Content-Type": "application/json"
        },
        "matchingRules": {
          "body": {
            "$.id": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "integer"
                }
              ]
            },
            "$.status": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "type"
                }
              ]
            },
            "$.total": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "decimal"
                }
              ]
            }
          }
        },
        "status": 200
      }
    },
    {
      "description": "a request for an unknown order",
      "providerStates": [
        {
          "name": "order 999 does not exist"
        }
      ],
      "request": {
        "method": "GET",
        "path": "/orders/999"
      },
      "response": {
        "status": 404
      }
    },
    {
      "description": "a request to create an order",
      "providerStates": [
        {
          "name": "orders can be created"
        }
      ],
      "request": {
        "body": {
          "items": [
            {
              "qty": 2,
              "sku": "BOOK-1"
            }
          ]
        },
        "headers": {
          "Content-Type": "application/json"
        },
        "matchingRules": {
          "body": {
            "$.items[0].qty": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "integer"
                }
              ]
            },
            "$.items[0].sku": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "type"
                }
              ]
            }
          }
        },
        "method": "POST",
        "path": "/orders"
      },
      "response": {
        "body": {
          "id": 1001,
          "status": "NEW",
          "total": 129.9
        },
        "headers": {
          "Content-Type": "application/json"
        },
        "matchingRules": {
          "body": {
            "$.id": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "integer"
                }
              ]
            },
            "$.status": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "type"
                }
              ]
            },
            "$.total": {
              "combine": "AND",
              "matchers": [
                {
                  "match": "decimal"
                }
              ]
            }
          }
        },
        "status": 201
      }
    }
  ],
  "metadata": {
    "pact-jvm": {
      "version": "4.7.7"
    },
    "pactSpecification": {
      "version": "3.0.0"
    }
  },
  "provider": {
    "name": "orders-producer"
  }
}
Every test that uses a @Pact method must exercise all of its interactions. My first version put the “order exists” and “order 999 does not exist” interactions in one @Pact method and called only the first from a test. Pact failed it with The following requests were not received. Each @Pact method should describe exactly the calls its test makes, which is why the file has three small methods.
Pact phones home by default. Verification logged a notice that Pact JVM is tracking events anonymously (JVM version, operating system). Set pact_do_not_track=true as a system property or environment variable if that matters to you; the lab’s run-all.sh does.

Four producer changes, two tools: what actually turns red

Now the part the contracts exist for. The producer reads ORDERS_VARIANT and changes its response. For each variant the script runs the whole producer test suite, which contains both the Spring Cloud Contract generated tests and the Pact verification. Same service, same four changes, both tools:
Producer changeSpring Cloud ContractPactTranscript
Add a new field discountpasses (3 of 3)passes (3 of 3)10
Rename total to totalAmountfails (2 of 3)fails (2 of 3)11
Remove items (no consumer reads it)fails (2 of 3)passes (3 of 3)12
total sent as the string "129.90"fails (2 of 3)fails (2 of 3)13
Adding a field is the case both tools allow, and it should be: additive changes are what keep APIs evolvable. The other three are worth looking at one by one.

Rename: both tools catch it, with different messages

Spring Cloud Contract fails the generated test and prints the actual body next to the JSON path it expected (11-variant-rename-total.txt):
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":42,"status":"CONFIRMED","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
Pact prints a diff of expected versus actual for the interaction:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 42,
          "status": "CONFIRMED",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }
The Pact message says what is missing (Actual map is missing the following keys: total) and shows the real response. The Spring Cloud Contract message tells you the JSON path that did not match. Both are good enough to find the cause in seconds.

Remove an unused field: the two philosophies diverge

This is the case that explains why people argue about these tools. The producer removes items, which checkout never reads. Spring Cloud Contract fails, because the producer’s own contract lists items (12-variant-drop-items.txt):
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.RuntimeException: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
Caused by: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
Pact passes, because the consumer never said it needed items:
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given order 42 exists and is confirmed
  a request for order 42
    returns a response which
      has status code 200 (OK)
      has a matching body (OK)

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given order 999 does not exist
  a request for an unknown order
    returns a response which
      has status code 404 (OK)
      has a matching body (OK)

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given orders can be created
  a request to create an order
    returns a response which
      has status code 201 (OK)
      has a matching body (OK)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
Neither result is wrong. Spring Cloud Contract treats the contract as the producer’s published promise, so removing anything it lists is a breaking change by definition. Pact treats the contract as the sum of what real consumers use, so the producer is free to remove what nobody reads. If you have many consumers and want producers to evolve freely, the Pact behaviour is what you want. If you want a stable, reviewed API surface, the Spring Cloud Contract behaviour is.

Type changes: Pact matches by type, so it notices a number turning into a string

When total becomes the string "129.90" both tools fail; Pact says so in one line (13-variant-total-string.txt):
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body

    1.1) body: $.total Expected '129.90' (String) to be a decimal number

A contract change that is green on the producer and red on the consumer

There is one more scenario, and it is the one that motivates CI step 4 below. Suppose the producer team renames total to totalAmount in the contract files and in the code. Their Spring Cloud Contract build goes green and publishes new stubs (21-evolved-contract-producer.txt; this run uses a scratch copy and only the generated tests, since the Pact check above would rightly block it):
[INFO] Running com.ankurm.contracts.orders.OrdersTest

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
The consumer’s next run against those stubs fails (22-evolved-contract-consumer.txt):
[INFO] Running com.ankurm.contracts.checkout.OrdersStubConsumerTest

[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.checkout.OrdersStubConsumerTest
[ERROR] com.ankurm.contracts.checkout.OrdersStubConsumerTest.amountDueComesFromTheStubbedOrder -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError: 

Expecting actual not to be null
Only one of three tests failed, and the message is a null, not a clear error: Jackson ignores the unknown totalAmount, and Order.total is simply null. If the consumer had not re-run against fresh stubs, this would have reached production.
Going deeper: the complete output of the rename run Both tools in one run (11-variant-rename-total.txt). The string-total run is in 13-variant-total-string.txt in the same format:
[INFO] Running com.ankurm.contracts.orders.OrdersTest

[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":42,"status":"CONFIRMED","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]

[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldCreateOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":1001,"status":"NEW","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]

[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given order 42 exists and is confirmed
  a request for order 42
    returns a response which
      has status code 200 (OK)
      has a matching body (FAILED)

Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 42,
          "status": "CONFIRMED",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given order 999 does not exist
  a request for an unknown order
    returns a response which
      has status code 404 (OK)
      has a matching body (OK)

Verifying a pact between checkout-consumer and orders-producer
  [Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
  Given orders can be created
  a request to create an order
    returns a response which
      has status code 201 (OK)
      has a matching body (FAILED)

Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 1001,
          "status": "NEW",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

[ERROR] Tests run: 3, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[1] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError: 
checkout-consumer - Upon a request for order 42 
Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 42,
          "status": "CONFIRMED",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[3] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError: 
checkout-consumer - Upon a request to create an order 
Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 1001,
          "status": "NEW",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

[ERROR] Failures: 
[ERROR]   OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request for order 42 
Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 42,
          "status": "CONFIRMED",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

[ERROR]   OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request to create an order 
Failures:

1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body

    1.1) body: $ Actual map is missing the following keys: total

        {
          "id": 1001,
          "status": "NEW",
        -  "total": 129.9
        +  "totalAmount": 129.90
        }

[ERROR] Errors: 
[ERROR]   OrdersTest.validate_shouldCreateOrder:40 ? IllegalState Parsed JSON [{"id":1001,"status":"NEW","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR]   OrdersTest.validate_shouldReturnOrder:87 ? IllegalState Parsed JSON [{"id":42,"status":"CONFIRMED","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] Tests run: 6, Failures: 2, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE

Wiring it into CI: the order matters

Contract tests only protect you if they run in the right order, because the two tools hand artefacts between the builds. The order the lab uses is in run-all.sh and boils down to four steps:
run checkout-consumer 02-consumer-pact-run.txt -- clean test -Dtest=OrdersPactConsumerTest
cp checkout-consumer/target/pacts/checkout-consumer-orders-producer.json orders-producer/src/test/resources/pacts/
run orders-producer 04-producer-baseline.txt -- clean install
run checkout-consumer 08-consumer-stub-run.txt -- clean test -Dtest=OrdersStubConsumerTest
1 consumer buildwrites pact file2 producer buildverify pact + gen tests3 publishstubs jar (install)4 consumer buildtests vs new stubsA failure at step 2 blocks the producer from publishing. A failure at step 4 tells the consumer team the producer moved.Step 4 is the one teams forget: without it a producer contract change is invisible to the consumer until production.Not run in this lab: a Pact Broker, can-i-deploy, a hosted CI server. The order above is what the script runs locally.
Read the diagram left to right. Step 1 produces the pact, step 2 consumes it and also produces the stubs, step 4 consumes the stubs. The run in those lines is the script’s helper that runs Maven inside a module and filters the output, and the lines above are copied from the script.
  • Producer pipeline. Run mvn verify (generated tests, Pact verification), then publish the stubs jar to your artifact repository with mvn deploy. A red build here means the producer broke a promise.
  • Consumer pipeline. Run the Pact consumer tests and publish the pact; run the stub-runner tests against + (latest) stubs. The second one is what catches the scenario in the previous section.
  • Trigger the other side. A new pact should trigger producer verification, and new stubs should trigger consumer runs. Without that, the tests only run when someone happens to push.
What was not run. This lab does not use a Pact Broker, can-i-deploy, or a hosted CI server; the pact travels by file copy and the stubs through the local Maven repository. Those are the right tools once more than two services are involved, and the Pact docs on can-i-deploy describe the gate. I did not run them, so I make no claims about their behaviour here.
Always clean after editing a contract. While building this lab, a non-clean mvn test after an earlier build compiled and ran only the Pact test; OrdersTest was missing from target/test-classes and a -Dtest=OrdersTest run reported that no tests matched. The Spring Cloud Contract plugin had logged that nothing needed generating. A clean build fixed it. I did not dig into the root cause, so treat the incremental-build behaviour as a trap rather than a diagnosis.

The Boot 4.2 trap: Spring Cloud Contract 5.0.3 crashes inside REST Assured

The first time the generated tests ran on Spring Boot 4.2.0, two of the three failed with a bare NullPointerException thrown from inside Groovy, not from anything in the test. It comes from the REST Assured version Spring Cloud Contract 5.0.3 brings (5.5.7), running against the Groovy 5.1.3 that Spring Boot 4.2 manages. The POST contract passed in the same run and I did not investigate why. I reproduced the failure deliberately with -Drest-assured.version=5.5.7 (20-restassured-5-groovy-5.txt):
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.NullPointerException
When I read the surefire report during the build, the top frames were org.codehaus.groovy.runtime.metaclass.ClosureMetaClass called from REST Assured’s HTTPBuilder (the report is not committed). Importing REST Assured’s own BOM at 7.0.0, ahead of the Spring Cloud Contract BOM, fixes it; the three generated tests then pass. This is the block in the producer POM (pom.xml):
      <!-- Spring Cloud Contract 5.0.3 ships REST Assured 5.5.7, which breaks on the Groovy 5.1.x that
           Spring Boot 4.2 manages (NullPointerException inside Groovy's ClosureMetaClass). REST Assured 7 does not. -->
      <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured-bom</artifactId>
        <version>${rest-assured.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
I did not investigate which Groovy API changed, so I cannot say whether a Groovy 4 pin would also work; the REST Assured 7.0.0 import is what I verified. If you see an unexplained NPE from generated tests after a Boot upgrade, check the REST Assured and Groovy versions first.

Spring Cloud Contract is leaving the Spring Cloud release train: what that means for you

On 6 July 2026 the Spring team announced that maintenance and ownership of Spring Cloud Contract had been transferred to Marcin Grzejszczak, one of its original creators, under a project called Stubborn Contract. According to the announcement on spring.io, Spring Cloud Contract will be removed from future Spring Cloud release trains and Spring will stop providing updates for it in existing trains. I checked what that looks like in practice: the spring-cloud-dependencies 2026.0.0 BOM I resolved on Spring Boot 4.2.0 contains no Spring Cloud Contract entries, so you have to pin spring-cloud-contract-dependencies yourself (5.0.3 is the latest version on Maven Central today), as the POMs in this lab do. The 2026.0 documentation page still links to the reference docs, so the project is not gone from the docs, just from the BOM. Stubborn Contract keeps the model: contracts in YAML, Groovy or Java DSL, the same generated WireMock stubs, the same stub runner. The coordinates move to sh.stubborn. I ran the exact same producer sources, contracts and consumer code under Stubborn Contract 0.2.4, using pom-stubborn.xml in each module (pom-stubborn.xml and pom-stubborn.xml). Producer (30-stubborn-producer.txt):
[INFO] Using the model-based test generator [stubborn.contract.verifier.model-based-generator != false]
[INFO] Running com.ankurm.contracts.orders.OrdersTest

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
Consumer, using stubs the Stubborn build published (31-stubborn-consumer.txt):
[INFO] Running com.ankurm.contracts.checkout.OrdersStubbornConsumerTest

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersStubbornConsumerTest
Two findings from the migration, both from running it. First, the YAML contracts needed no changes, and the producer needed no source changes at all, only the POM. Second, the stub runner’s StubsMode enum moved: in Spring Cloud Contract it is nested in StubRunnerProperties; in Stubborn Contract 0.2.4 it is a top-level class in sh.stubborn.contract.stubrunner. A plain package rename leaves the consumer test failing to compile with cannot find symbol: variable StubsMode. The consumer test imports end up like this (OrdersStubbornConsumerTest.java):
import sh.stubborn.contract.stubrunner.spring.AutoConfigureStubRunner;
import sh.stubborn.contract.stubrunner.StubsMode;
Also useful: the Stubborn BOM manages a REST Assured version that works with Boot 4.2’s Groovy, so the override from the previous section is not needed on the Stubborn build (the resolved versions are in 01-versions.txt: REST Assured 6.3.0 on Groovy 5.1.3, and the generated tests passed without my REST Assured import).
Which should a new project use? Stubborn Contract 0.2.4 is a 0.x release, tested by its authors with Spring Boot 4.1 and, as shown here, working on 4.2.0 for this small case. Spring Cloud Contract 5.0.3 works on Boot 4.2.0 with one override but receives no further updates according to Spring. For a new project I would start on Stubborn Contract; for an existing one there is no urgency, because Stubborn states that existing contracts and stub-runner configuration keep working and that you can stay on your current versions while you plan the move. I only tested one small service pair; I have not tested messaging contracts or the Gradle plugin.
Going deeper: the artefact mapping from the Stubborn migration guide The table below is transcribed from the Stubborn migration guide; the first four rows I also used in this lab. The guide also says legacy spring.cloud.contract.stubrunner.* properties still bind with a deprecation warning, and that plugin <configuration> blocks are unchanged. I did not use stub-runner properties, so I did not test that claim.
Spring Cloud ContractStubborn Contract
spring-cloud-contract-maven-pluginsh.stubborn:stubborn-contract-maven-plugin
spring-cloud-starter-contract-verifiersh.stubborn:stubborn-contract-starter-verifier
spring-cloud-starter-contract-stub-runnersh.stubborn:stubborn-contract-starter-stub-runner
spring-cloud-dependencies (BOM)sh.stubborn:stubborn-contract-dependencies
package org.springframework.cloud.contractpackage sh.stubborn.contract

Which one should you use?

The runs above give the decision most of its content. Use this as a starting point, not a verdict:
If this is youLean towards
You own both services, or one team owns the API and wants a reviewed, stable surfaceSpring Cloud Contract / Stubborn Contract. The contract is a producer-owned file; removing a listed field is a visible, deliberate act
Many consumers, different teams, producers should be free to change what nobody usesPact. Each consumer pins only what it reads; the producer sees exactly who depends on what
Consumers are not all Java (Node, mobile, Go)Pact. It has implementations for many languages; Spring Cloud Contract’s stub runner is a JVM library
You want ready-made WireMock stubs for consumer tests with no extra codeSpring Cloud Contract / Stubborn Contract. The stubs jar is the product
You need a gate like “can this version go to production?” across several servicesPact with a Pact Broker and can-i-deploy (not run in this lab); Stubborn also describes a commercial broker for that
The honest comparison from the runs: Spring Cloud Contract was stricter (it failed on an unused field Pact let through) and Pact was more precise about types (one line naming the field and the expected type). Neither made the consumer’s second problem, running against fresh stubs, go away.
Should you do this at all? Contract tests earn their keep when two teams change services on different schedules. If one team owns both sides and deploys them together, a shared integration test or a type-checked client generated from one OpenAPI file is simpler. Do not add a contract tool for a single internal call between two modules in one repository: a plain @SpringBootTest that calls both is cheaper and tests more. And remember what a contract cannot see: it checks the shape of one conversation, not whether the producer’s business logic is right.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.