Notes
The roles
Two roles. The consumer is the code that calls an API: a web app, a mobile app or another service. The provider is the API that answers. ShopRung has both: its web page's JavaScript is a consumer of the ShopRung API. A contract is the list of requests the consumer makes, and the parts of each response it actually relies on. Not the whole response; only what the consumer uses.
- consumer: code that CALLS an API (web app, mobile app, another service)
- provider: the API answering
- ShopRung: the web page's app.js is a consumer of the ShopRung API
- contract = the requests the consumer makes + the parts of responses it relies on
Step 1: consumer test
Step one runs on the consumer side. The test describes an interaction: given product one exists, upon receiving a get for product one, respond two hundred with an id, a sku and a price in cents. Pact starts a mock server that answers exactly that. The consumer's real code calls the mock, and the test checks it handles the answer. If the test passes, Pact writes the interaction to a pact file. Ours passed and wrote shoprung web, shoprung api dot json.
pact = Pact("shoprung-web",
"shoprung-api")
(pact.upon_receiving("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", ...),
"priceCents": match.int(1250)}))
with pact.serve() as srv:
assert get_price(srv.url, 1) == ... Matchers
Matchers keep contracts from being brittle. Match int twelve fifty means any integer, with twelve fifty as the example the mock returns. Match regex says the sku must look like two letters, a dash and three digits. Each like describes an array whose items all look like an example. The pact file stores the examples and these matching rules, so the provider can return any real product and still pass, as long as the shape is right.
match.int(1250)
any integer (1250 = example)
match.regex("BK-101",
regex=r"^[A-Z]{2}-\d{3}$")
match.str("Clean Code ...")
match.each_like({...})
array of items like this
pact file stores examples
+ "matchingRules" Step 2: verify provider
Step two runs on the provider side, with no consumer code at all. The verifier reads the pact file, replays each request against the real provider, and checks each response against the rules. We verified our pact against the real ShopRung API: status two hundred, OK; content type header, OK; matching body, OK. Extra fields the consumer does not use, like name and stock, are fine, because the consumer does not rely on them.
Verifier("shoprung-api")
.add_transport(url=BASE)
.add_source("pacts/").verify()
a request for product 1
Given product 1 exists
has status code 200 (OK)
includes headers
"Content-Type" (OK)
has a matching body (OK) A broken contract
Then we broke it on purpose. A new consumer version expected an image URL field for product pictures, which the ShopRung API does not send. The consumer test still passed, because the mock returns whatever the contract says. But provider verification failed: the actual map is missing the following keys, image URL, with a diff. That is the bug caught before deployment, without starting a browser or the whole system.
has a matching body (FAILED)
1.1) has a matching body
$ -> Actual map is missing
the following keys:
imageUrl
- "imageUrl": "x.png",
+ "category": "Books",
+ "inStock": true, Provider states
Interactions can name a provider state, like product one exists, or Alice has an order. Before replaying that interaction, the provider's verification calls a state handler that sets up the data, for example through a test endpoint or the database. For ShopRung, a reset makes product one exist. Without provider states, verification depends on whatever data happens to be there, which makes it flaky.
- each interaction can say given("product 1 exists") given("alice has an order")
- the provider registers a handler per state that creates or resets the data
- ShopRung: POST /api/test/reset makes "product 1 exists" true
In Java
Java teams use Pact JVM with JUnit five, and the steps are the same. The consumer test is annotated with the Pact consumer extension, and a Pact method builds the interaction with a builder: given, upon receiving, will respond with. The provider test names the provider, says where the pact files are, and has a method per provider state, annotated with State. A test template verifies every interaction.
// consumer
@ExtendWith(PactConsumerTestExt.class)
@Pact(consumer = "shoprung-web")
V4Pact product(PactDslWithProvider b)
{ return b.given("product 1 exists")
.uponReceiving(...)...toPact(); }
// provider
@Provider("shoprung-api")
@PactFolder("pacts")
@State("product 1 exists")
void reset() { ... } In CI
In real teams, consumer and provider live in different repositories. A Pact Broker, self hosted or as a hosted service, shares the contracts. Consumer CI runs its tests and publishes the pact. Provider CI fetches every pact that names it, verifies, and publishes the results. Before either side deploys, the can I deploy command asks the broker whether that version is compatible with what is already in the target environment.
- consumer CI: test, then publish pact to the broker
- provider CI: fetch all pacts for it, verify, publish the results
- before deploying either side: pact-broker can-i-deploy → yes only if versions in that environment agree
Common mistakes
Mistakes to avoid. Exact values instead of matchers, which breaks on every data change. Contracts that list fields the consumer never uses, which blocks the provider for no reason. Using Pact to test business logic, like discount rules; that belongs in functional API tests. No provider states. Publishing contracts but never running can I deploy. And adopting it on one side only: contract testing needs both teams.
- exact values instead of matchers (brittle)
- contracts listing fields the consumer never uses
- using Pact to test provider business logic
- no provider states
- never running can-i-deploy
- one team only: no consumer
Say it like this
In the interview: contract testing checks that a consumer and a provider agree, with each tested separately. In consumer driven contracts, the consumer's test runs against a Pact mock and records the requests and the response fields it relies on, using matchers. The provider replays them against its real API, with provider states for data. A broker shares pacts, and can I deploy blocks incompatible releases. It replaces many slow end to end tests, not functional tests.
- "Consumer-driven contracts: the consumer test runs against
- a Pact mock and records the requests and the response
- fields it relies on. The provider replays them against
- its real API with provider
- states. A broker shares pacts
- and can-i-deploy blocks
- incompatible releases."