QA and Test Automation · Lab 12 of 35

Contract Testing With Pact: Hands-On Lab on ShopRung

Write a consumer-driven contract between ShopRung's web shop and its API with Pact: a consumer test against a Pact mock that writes the pact file, matchers instead of exact values, provider verification against the real API with a provider state, and a broken contract caught with an exact diff.

⏱ 60 minAdvanced💸 Free7 stepsJava + Python

Java 21 + MavenPact JVM 4.6 (JUnit 5)JacksonPython 3.12 + pact-python 4.2 (second path)ShopRung

Overview video

1 / 6

0 of 7 steps done

What you will build

Both halves of a contract test, in one project:

  • The consumer: a small ProductClient that reads a product's SKU and price, the way ShopRung's web page does, and a consumer test that runs it against a Pact mock server and writes the contract to a pact file.
  • The provider check: a test that replays every interaction in the pact against the real ShopRung, after setting up the provider state "product 1 exists".

Then you break the contract on purpose (the consumer starts expecting an imageUrl field) and watch provider verification fail with Actual map is missing the following keys: imageUrl, before anything is deployed.

Before you start

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start. In this lab ShopRung plays the provider: the API that answers.

Run
curl http://localhost:8080/api/health
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}

S2Make the project

Java: make the Maven folders. Python: make a folder with a tests folder, create a virtual environment and activate it.

Run
# Java
mkdir -p shoprung-pact/src/main/java/dev/algorung/shop shoprung-pact/src/test/java/dev/algorung/shop
# Python
mkdir -p shoprung-pact-py/tests && cd shoprung-pact-py && python3 -m venv .venv && source .venv/bin/activate
1

Dependencies for both sides

A project with the Pact libraries for the consumer test and the provider check.

In real teams the consumer and the provider live in different repositories, owned by different teams. To learn the flow, this lab keeps both halves in one project.

Java: pom.xml brings Pact JVM's two JUnit 5 modules: consumer:junit5 (a mock server plus the pact writer) and provider:junit5 (the verifier). Jackson is a normal dependency because the consumer's own code reads JSON with it.

Python: requirements.txt pins pact-python, which bundles the Pact engine (written in Rust), plus httpx for the client.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.algorung</groupId>
  <artifactId>shoprung-pact</artifactId>
  <version>0.1.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.11.4</junit.version>
    <pact.version>4.6.17</pact.version>
    <jackson.version>2.18.2</jackson.version>
  </properties>

  <dependencies>
    <!-- the consumer's own code reads JSON with Jackson -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- consumer side: a Pact mock server and the pact file writer -->
    <dependency>
      <groupId>au.com.dius.pact.consumer</groupId>
      <artifactId>junit5</artifactId>
      <version>${pact.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- provider side: replays pact files against the real API -->
    <dependency>
      <groupId>au.com.dius.pact.provider</groupId>
      <artifactId>junit5</artifactId>
      <version>${pact.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
    </plugins>
  </build>
</project>
  1. Both Pact modules on one version.line 14
  2. Consumer side: PactConsumerTestExt, the DSL and the mock server.line 34
  3. Provider side: replays pact files against a running API.line 41
2

The consumer's code

A small client that reads product 1's SKU and price: the code the contract protects.

A contract test checks real consumer code, not a test helper. Here the consumer is a client like the one ShopRung's web page uses: it calls GET /api/products/{id} and keeps only two fields, sku and priceCents. Those two fields are all this consumer relies on, so they are all the contract will contain. ShopRung also sends name, category, stock and more; the consumer does not care, so the contract will not mention them.

src/main/java/dev/algorung/shop/ProductClient.java
package dev.algorung.shop;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/** The consumer: code in the ShopRung web shop that reads a product from the API. */
public class ProductClient {
    public record Product(String sku, long priceCents) {}

    private final String baseUrl;
    private final HttpClient http = HttpClient.newHttpClient();
    private final ObjectMapper json = new ObjectMapper();

    public ProductClient(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public Product product(int id) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/api/products/" + id)).build();
        HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200) throw new IOException("GET product " + id + ": HTTP " + response.statusCode());
        JsonNode body = json.readTree(response.body());
        return new Product(body.get("sku").asText(), body.get("priceCents").asLong());
    }
}
  1. What the consumer needs: two fields.line 13
  2. The base URL is a parameter, so the test can point the client at the Pact mock.line 24
  3. The consumer reads these two fields and ignores the rest.line 28
3

The consumer test writes the contract

The client passes against a Pact mock, and the pact file appears.

The consumer test describes one interaction: given the provider state product 1 exists, upon receiving GET /api/products/1, respond 200 with an id, a sku and a priceCents. Pact starts a mock server that answers exactly that. The test points the real ProductClient at the mock and checks it reads BK-101 and 1250.

When the test passes, Pact writes the interaction to a pact file: target/pacts/shoprung-web-shoprung-api.json in Java, pacts/shoprung-web-shoprung-api.json in Python. That file is the contract.

Look at the matchers: integerType (match.int) means "any integer, for example 1250"; stringMatcher (match.regex) means "a string like two capitals, a dash and three digits". The provider can return any real product and still pass, as long as the shape is right. Exact values would make the contract break every time the data changes.

src/test/java/dev/algorung/shop/ProductClientPactTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;

import au.com.dius.pact.consumer.MockServer;
import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.PactSpecVersion;
import au.com.dius.pact.core.model.V4Pact;
import au.com.dius.pact.core.model.annotations.Pact;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

/** Consumer side: our ProductClient against a Pact mock. Writes target/pacts/shoprung-web-shoprung-api.json. */
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "shoprung-api", pactVersion = PactSpecVersion.V4)
class ProductClientPactTest {

    @Pact(consumer = "shoprung-web")
    V4Pact productOne(PactDslWithProvider builder) {
        return builder
                .given("product 1 exists")
                .uponReceiving("a request for product 1")
                    .path("/api/products/1")
                    .method("GET")
                .willRespondWith()
                    .status(200)
                    .body(new PactDslJsonBody()
                            .integerType("id", 1)
                            .stringMatcher("sku", "^[A-Z]{2}-\\d{3}$", "BK-101")
                            .integerType("priceCents", 1250))
                .toPact(V4Pact.class);
    }

    @Test
    @PactTestFor(pactMethod = "productOne")
    void readsSkuAndPriceOfProduct1(MockServer mockServer) throws Exception {
        ProductClient client = new ProductClient(mockServer.getUrl());
        assertEquals(new ProductClient.Product("BK-101", 1250), client.product(1));
    }
}
  1. Who we expect to talk to, and the Pact spec version.line 18
  2. The method that builds the contract.line 21
  3. A provider state: the provider sets this up before replaying.line 24
  4. Any integer; 1 is only the example the mock returns.line 31
  5. Any string matching the regex.line 32
  6. The real client code, pointed at the mock.line 40
Run
mvn test -Dtest=ProductClientPactTest
ls target/pacts
You should seeyour text will differ: the model writes it
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
shoprung-web-shoprung-api.json
4

Read the pact file

Know what a contract really contains.

Open the pact file. It is plain JSON, which is why it can be shared, versioned and reviewed. The important parts (shortened):

{
  "consumer": { "name": "shoprung-web" },
  "provider": { "name": "shoprung-api" },
  "interactions": [{
    "description": "a request for product 1",
    "providerStates": [{ "name": "product 1 exists" }],
    "request": { "method": "GET", "path": "/api/products/1" },
    "response": {
      "status": 200,
      "body": { "content": { "id": 1, "priceCents": 1250, "sku": "BK-101" } },
      "matchingRules": { "body": {
        "$.id": { "matchers": [{ "match": "integer" }] },
        "$.priceCents": { "matchers": [{ "match": "integer" }] },
        "$.sku": { "matchers": [{ "match": "regex", "regex": "^[A-Z]{2}-\\d{3}$" }] }
      } }
    }
  }]
}

The example values (1250, BK-101) are what the mock returned. The matchingRules say what the provider must satisfy: $.priceCents must be an integer, $.sku must match the regex. Fields the consumer never mentioned (name, stock) are not in the file, so the provider is free to change them.

5

Verify the real provider

The pact replayed against the running ShopRung: status, headers and body all OK.

Now the provider side. This test has no consumer code at all. It reads every pact file in the pact folder, and for each interaction it first calls the state handler for the interaction's provider state, then sends the recorded request to ShopRung and checks the response against the matching rules.

The state handler for product 1 exists resets ShopRung to its seed data, where product 1 is the Clean Code Notebook. Without provider states, verification would depend on whatever data happens to be there.

Java: @IgnoreNoPactsToVerify keeps the class from failing before any pact exists; that is also why the methods check context != null. Run the consumer test first, then this one. Python: the test skips itself until a pact exists; pytest runs test_consumer.py before test_provider.py, so one run does both.

src/test/java/dev/algorung/shop/ShopRungProviderPactTest.java
package dev.algorung.shop;

import au.com.dius.pact.provider.junit5.HttpTestTarget;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junitsupport.IgnoreNoPactsToVerify;
import au.com.dius.pact.provider.junitsupport.Provider;
import au.com.dius.pact.provider.junitsupport.State;
import au.com.dius.pact.provider.junitsupport.loader.PactFolder;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;

/** Provider side: replay every pact in target/pacts against the real, running ShopRung. */
@Provider("shoprung-api")
@PactFolder("target/pacts")
@IgnoreNoPactsToVerify
class ShopRungProviderPactTest {
    static final URI BASE = URI.create(System.getProperty("baseUrl", "http://localhost:8080"));

    @BeforeEach
    void target(PactVerificationContext context) {
        if (context != null) context.setTarget(new HttpTestTarget(BASE.getHost(), BASE.getPort()));
    }

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void verifyInteraction(PactVerificationContext context) {
        if (context != null) context.verifyInteraction();
    }

    @State("product 1 exists")
    void product1Exists() throws Exception {
        HttpClient.newHttpClient().send(
                HttpRequest.newBuilder(BASE.resolve("/api/test/reset")).POST(HttpRequest.BodyPublishers.noBody()).build(),
                HttpResponse.BodyHandlers.discarding());
    }
}
  1. Verify the pacts that name this provider.line 19
  2. Where the consumer test wrote them. In teams: a Pact Broker instead.line 20
  3. The real, running API.line 27
  4. One run of this template per interaction in the pacts.line 33
  5. Called before each interaction that names this state.line 36
Run
mvn test -Dtest=ShopRungProviderPactTest
You should seeyour text will differ: the model writes it
Verifying a pact between shoprung-web and shoprung-api
  [Using File target/pacts/shoprung-web-shoprung-api.json]
  Given product 1 exists
  a request for product 1
    returns a response which
      has status code 200 (OK)
      has a matching body (OK)
...
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Stuck on this step?
Python: verification hangs.
A state handler that raises makes the verifier retry. Check its signature is (action, parameters=None) and that ShopRung is reachable from it.
Java: "No pact files were found".
Run the consumer test first (mvn test -Dtest=ProductClientPactTest); it writes target/pacts. mvn clean deletes them.
6

Break the contract on purpose

A new consumer expectation the provider cannot meet, caught before deployment.

Imagine the web team wants product pictures and starts reading an imageUrl field. Add one line to the consumer's expected body, right after priceCents:

// Java, in ProductClientPactTest
        .stringType("imageUrl", "notebook.png")

# Python, in test_consumer.py
                "imageUrl": match.str("notebook.png"),

Run both tests again. The consumer test still passes: the mock answers whatever the contract says, so the web team's own tests are green. But provider verification fails: ShopRung does not send imageUrl. The failure names the missing key and shows a diff. In a real pipeline this blocks the web release until the API team adds the field. Remove the line again afterwards.

Run
mvn test -Dtest=ProductClientPactTest
mvn test -Dtest=ShopRungProviderPactTest
You should seeyour text will differ: the model writes it
      has a matching body (FAILED)
...
    $ -> Actual map is missing the following keys: imageUrl
...
[ERROR] Tests run: 1, Failures: 1
Why this way? End-to-end tests would find this too, but only after deploying both sides to a shared environment. The contract finds it in seconds, in the consumer's own pipeline.
7

How teams run this: the broker and can-i-deploy

The workflow around the tests you just wrote.

With two teams and two repositories, a folder of pact files is not enough. Teams use a Pact Broker (self-hosted, or a hosted service):

  1. The consumer's CI runs the consumer test and publishes the pact to the broker, tagged with the consumer's version.
  2. The provider's CI fetches every pact that names it, verifies them against its build, and publishes the results.
  3. Before either side deploys, pact-broker can-i-deploy asks the broker whether this version is verified against the versions already in that environment. If not, the deploy stops.

In the provider test, @PactFolder becomes @PactBroker with the broker's URL, and nothing else changes.

Check it works

Your contract tests work when all three are true:

  • The consumer test passes and writes shoprung-web-shoprung-api.json.
  • Provider verification against ShopRung passes, with the state handler called (the reset runs before the request).
  • Adding the imageUrl expectation keeps the consumer test green but fails provider verification with missing the following keys: imageUrl.
Test
mvn test -Dtest=ProductClientPactTest
mvn test -Dtest=ShopRungProviderPactTest
You should see
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
...
      has a matching body (OK)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

Troubleshooting

Provider verification fails on a value, like priceCents 1250 vs 1300.

You used exact values. Use type and regex matchers (integerType, match.int) so any valid product passes.

Verification fails because data is missing.

The provider state handler did not run or did not set up the data. Check the state name matches the consumer's given(...) exactly.

Java: the provider test reports "No tests found".

There is no pact yet and @IgnoreNoPactsToVerify skipped it. Run the consumer test first.

Python: ImportError for shop_client.

Run pytest from the project folder; pytest.ini has pythonpath = ..

What changes in production

  • Consumer and provider are separate repositories; pacts travel through a Pact Broker, never by copying files.
  • Each consumer publishes only what it uses. The provider verifies every consumer's pacts on every build.
  • can-i-deploy gates every deployment, so incompatible versions never reach the same environment.
  • Contract tests replace many slow end-to-end checks of service interfaces, but not functional tests of business rules like discounts.

Interview angle

“How does consumer-driven contract testing work, and when would you use it?”

The consumer writes a test against a Pact mock that records the requests it makes and the response fields it relies on, using type and regex matchers; passing writes a pact file. The provider replays every pact against its real API, using provider states to set up data, and fails with a diff if it cannot satisfy a consumer. A broker shares pacts and results, and can-i-deploy blocks incompatible releases. I use it between services owned by different teams, where end-to-end tests would be slow and late; business rules stay in functional tests.

Clean up

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip) Download Python project (.zip)