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
What you will build
Both halves of a contract test, in one project:
- The consumer: a small
ProductClientthat 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
- The idea first: Contract testing with Pact. It explains consumers, providers, pact files and the broker.
- Java path: Your first Java test project (JDK 21 and Maven). Python path: Python 3.12 and pytest, as in the pytest API lab.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start. In this lab ShopRung plays the provider: the API that answers.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"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.
# 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# 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# Java
mkdir shoprung-pact\src\main\java\dev\algorung\shop, shoprung-pact\src\test\java\dev\algorung\shop
# Python
mkdir shoprung-pact-py\tests; cd shoprung-pact-py; py -m venv .venv; .venv\Scripts\Activate.ps1 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.
<?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> - Both Pact modules on one version.line 14
- Consumer side:
PactConsumerTestExt, the DSL and the mock server.line 34 - Provider side: replays pact files against a running API.line 41
pytest==8.3.4
httpx==0.28.1
pact-python==4.2.0 - Bundles the Pact engine: nothing else to install.line 3
.venv/
__pycache__/ [pytest]
testpaths = tests
pythonpath = . - So tests can import
shop_clientfrom the project folder.line 3
Python version of this step:
pip install -r requirements.txt Successfully installed ... httpx-0.28.1 pact-python-4.2.0 ... pytest-8.3.4
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.
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());
}
} - What the consumer needs: two fields.line 13
- The base URL is a parameter, so the test can point the client at the Pact mock.line 24
- The consumer reads these two fields and ignores the rest.line 28
"""The consumer: code in the ShopRung web shop that reads a product from the API."""
from dataclasses import dataclass
import httpx
@dataclass
class Product:
sku: str
price_cents: int
def get_product(base_url: str, product_id: int) -> Product:
r = httpx.get(f"{base_url}/api/products/{product_id}", timeout=10)
r.raise_for_status()
body = r.json()
return Product(sku=body["sku"], price_cents=body["priceCents"]) - What the consumer needs: two fields.line 8
- The base URL is a parameter, so the test can use the Pact mock.line 13
Python version of this step:
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.
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));
}
} - Who we expect to talk to, and the Pact spec version.line 18
- The method that builds the contract.line 21
- A provider state: the provider sets this up before replaying.line 24
- Any integer; 1 is only the example the mock returns.line 31
- Any string matching the regex.line 32
- The real client code, pointed at the mock.line 40
"""Consumer side: our client against a Pact mock. Writes pacts/shoprung-web-shoprung-api.json."""
from pathlib import Path
from pact import Pact, match
from shop_client import Product, get_product
PACTS = Path(__file__).parent.parent / "pacts"
def test_reads_sku_and_price_of_product_1():
pact = Pact("shoprung-web", "shoprung-api").with_specification("V4")
(
pact.upon_receiving("a request for product 1")
.given("product 1 exists")
.with_request("GET", "/api/products/1")
.will_respond_with(200)
.with_body(
{
"id": match.int(1),
"sku": match.regex("BK-101", regex=r"^[A-Z]{2}-\d{3}$"),
"priceCents": match.int(1250),
},
content_type="application/json",
)
)
with pact.serve() as mock:
assert get_product(str(mock.url), 1) == Product(sku="BK-101", price_cents=1250)
pact.write_file(PACTS) - Consumer and provider names: they become the file name.line 12
- A provider state: the provider sets this up before replaying.line 15
- Any integer; 1 is only the example the mock returns.line 20
- Any string matching the regex.line 21
- The real client code, pointed at the mock.line 28
Python version of this step:
mvn test -Dtest=ProductClientPactTest
ls target/pacts [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS shoprung-web-shoprung-api.json
pytest -q tests/test_consumer.py
ls pacts . [100%] 1 passed in 0.04s shoprung-web-shoprung-api.json
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.
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.
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());
}
} - Verify the pacts that name this provider.line 19
- Where the consumer test wrote them. In teams: a Pact Broker instead.line 20
- The real, running API.line 27
- One run of this template per interaction in the pacts.line 33
- Called before each interaction that names this state.line 36
"""Provider side: replay every pact in pacts/ against the real ShopRung."""
import os
from pathlib import Path
import httpx
import pytest
from pact import Verifier
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
PACTS = Path(__file__).parent.parent / "pacts"
def product_1_exists(action, parameters=None):
"""Provider state: the seed data has product 1."""
if action == "setup":
httpx.post(f"{BASE_URL}/api/test/reset", timeout=10).raise_for_status()
def test_shoprung_honours_its_pacts():
if not list(PACTS.glob("*.json")):
pytest.skip("no pacts yet: run tests/test_consumer.py first, it writes them")
verifier = (
Verifier("shoprung-api")
.add_transport(url=BASE_URL)
.add_source(PACTS)
.state_handler({"product 1 exists": product_1_exists}, teardown=False)
)
verifier.verify() # raises with a diff if any interaction does not match - The state handler's arguments must be named
actionandparameters: Pact passes them by name.line 13 - Skip, with a reason, until the consumer test has written a pact.line 21
- The real, running API.line 24
- Called before each interaction with this state.line 26
Python version of this step:
mvn test -Dtest=ShopRungProviderPactTest 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 pytest -q -s Verifying a pact between shoprung-web and shoprung-api
a request for product 1 (0s loading, 65ms verification)
Given product 1 exists
returns a response which
has status code 200 (OK)
includes headers
"Content-Type" with value "application/json" (OK)
has a matching body (OK)
2 passed in 0.55s 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 writestarget/pacts.mvn cleandeletes them.
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.
mvn test -Dtest=ProductClientPactTest
mvn test -Dtest=ShopRungProviderPactTest has a matching body (FAILED)
...
$ -> Actual map is missing the following keys: imageUrl
...
[ERROR] Tests run: 1, Failures: 1 pytest -q has a matching body (FAILED)
$ -> Actual map is missing the following keys: imageUrl
- "imageUrl": "notebook.png",
FAILED tests/test_provider.py::test_shoprung_honours_its_pacts - RuntimeError...
1 failed, 1 passed in 0.65s 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):
- The consumer's CI runs the consumer test and publishes the pact to the broker, tagged with the consumer's version.
- The provider's CI fetches every pact that names it, verifies them against its build, and publishes the results.
- Before either side deploys,
pact-broker can-i-deployasks 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
imageUrlexpectation keeps the consumer test green but fails provider verification with missing the following keys: imageUrl.
mvn test -Dtest=ProductClientPactTest
mvn test -Dtest=ShopRungProviderPactTest [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-deploygates 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.