API Testing
Contract Testing with Pact
A practical course on consumer-driven contract testing using Pact. Learners move from the problem contract testing solves, through writing consumer tests that generate a contract, to verifying that contract against a real provider, and finally to sharing contracts safely across teams with a broker and a CI pipeline. The course favors small, runnable examples over theory: every concept is tied to a concrete consumer or provider test written in a mainstream testing tool such as Jest, Pytest or JUnit, paired with the Pact library for that language. By the end, a learner can explain when contract testing replaces or complements end-to-end and integration tests, write and verify a contract for a simple HTTP API, and wire contract verification into a build so that a provider change that breaks a consumer is caught before release rather than in production.
Intermediate · By the Xtest team · About 26 minutes to read
Introduction
Modern systems are rarely a single application. A web front end calls a checkout service, which calls a payments service, which calls a shipping service, and each of those teams ships independently. End-to-end tests that spin up every service to check that two of them still agree on a request shape are slow, flaky, and tell you about a break only after all the pieces have been wired together. Contract testing takes a different approach: instead of testing the whole system together, each pair of services that talk to each other agrees on a contract describing the requests one side sends and the responses the other side returns. The consumer of an API writes tests against a mock of the provider; those tests record the exact requests and responses they rely on into a contract file. The provider then replays every recorded request against its own real code and checks that the responses still match. Neither side needs the other running to test against it, and because the contract is generated from real consumer expectations rather than guessed by the provider team, it stays honest. This course works through that cycle with Pact, the most widely used consumer-driven contract testing tool, covering what a contract actually captures, how to write a consumer test that generates one, how to verify it on the provider side, and how a contract broker lets many services share and gate their contracts safely in a CI pipeline. The goal is not just to run an example but to understand which testing problems contract testing solves, and which ones it deliberately leaves to other kinds of tests.
Why Contract Testing, and How Pact Works
Before writing a single test, it helps to place contract testing among the other kinds of tests a team already runs, and to understand the two-sided cycle Pact is built around.
The testing problem contract testing solves
A unit test checks a piece of code in isolation. An end-to-end test starts a consumer and a provider together and drives a real interaction between them. End-to-end tests are valuable but expensive: they are slow to run, need every dependency deployed and configured, and a failure can come from almost anywhere in the stack, so diagnosing it takes time. Worse, in a system with many services, testing every pair of them end-to-end does not scale: the number of pairs grows fast as services are added, and a flaky dependency three hops away can fail a test that has nothing to do with it.
Contract testing narrows the question. Instead of asking 'does the whole system work together right now', it asks 'does this provider still honour the exact requests this consumer depends on, and does this consumer still send requests the provider recognises'. That question can be answered without running the whole system, and it can be answered independently on each side, in each team's own build.
Consumer-driven contracts
Pact calls itself consumer-driven because the contract starts life in the consumer's test suite, not in a specification document the provider writes up front. The consumer team writes a test that describes, in code, the requests it will send and the responses it needs back. Running that test against a Pact mock provider produces a contract file, usually called a pact file, that records each of those request/response pairs as an interaction. The provider team then takes that same file and replays every interaction against their real, running service code, checking that the actual response matches what the consumer's test expected.
This ordering matters: the provider is never asked to guess what consumers need, and a consumer can never accidentally write a test against a request shape the provider does not actually support, because the provider verification step would fail.
What a pact file actually contains
A pact file is JSON. For each interaction it records a description, the consumer's request (method, path, headers, body), and the response the mock returned (status, headers, body) that the consumer's test asserted on. Pact's matching rules let a consumer say more than 'the body must be exactly this JSON': a field can be asserted to exist and have a given type, or match a given format, without pinning its exact value, which keeps the contract from being broken by changes that do not actually matter to the consumer, such as a timestamp or a generated id.
The two sides of the test
A consumer Pact test runs entirely on the consumer's side: it starts a lightweight mock HTTP server in-process, tells it which requests to expect and which responses to return, points the code under test at that mock instead of the real provider, and runs normal application code against it. If the test passes, the pact file is written to disk.
A provider Pact verification test runs on the provider's side: it starts the provider's real service (or a slice of it), reads the pact file, and for every interaction in it fires the recorded request at the real service and checks the real response against what the file says the consumer needs. No consumer code runs during verification; only the contract, as data, is needed.
What contract testing does not replace
Contract testing checks the shape and meaning of individual interactions a consumer actually exercises. It does not check that a whole user journey works end to end across several services, it does not check performance or load behaviour, and it will miss a bug that only shows up when several interactions are combined in a particular order. Keeping a small number of end-to-end tests for the journeys that matter most, alongside a larger suite of contract tests for the pairwise interactions, is the usual balance.
Consumer, Provider, and the Pact Broker
Three roles recur throughout contract testing with Pact, and it helps to fix the vocabulary before writing code.
The consumer is the side that calls an API: a web front end calling a checkout service, or one backend service calling another. The consumer owns the expectations, because it is the one that breaks if the response it depends on changes shape.
The provider is the side that serves the API: the checkout service in the example above. The provider owns the real behaviour, and its verification test is run against real application code, not a mock, so a passing verification is a strong signal that the provider truly behaves as the contract describes.
The Pact Broker is a separate, shared service that stores pact files and verification results. A consumer's build publishes its generated pact file to the broker after a passing consumer test. A provider's build fetches the latest relevant pact files from the broker, runs verification against them, and publishes the verification result back. The broker then lets either side query 'is it safe for me to deploy', because it knows, for every version of the consumer and every version of the provider, whether verification passed. This is what lets many teams share contracts without emailing JSON files around, and it is what a CI pipeline calls into before allowing a deploy to proceed.
Understanding this triangle, consumer test produces a contract, provider test verifies it, broker stores and connects the two, is the key to everything that follows in this course: every later section is really just adding detail to one corner of this picture.
Setting Up a First Pact Project
A minimal Pact setup needs three things: a Pact client library for the consumer's language, a Pact provider verifier for the provider's language, and somewhere to keep the resulting pact file while the course is run locally, before a broker is introduced.
For a JavaScript/Node project, the consumer side typically installs the @pact-foundation/pact package and writes its consumer test with a normal test runner such as Jest or Mocha. For a Python project, pact-python plays the same role with Pytest. For a JVM project, pact-jvm provides JUnit integration for both consumer and provider sides. Each language's Pact library follows the same shape: a PactV3 (or similarly named) object is configured with the consumer and provider names, interactions are registered on it with given, uponReceiving, withRequest, and willRespondWith, and the test body runs inside a block that starts the mock server, runs the assertions, and writes the pact file on success.
A sensible first project layout keeps the consumer test, the application code that calls the API, and a pacts output directory in the consumer's repository, and keeps a separate provider verification test, driven from the same pact file, in the provider's repository. Running the consumer test first produces the pact file; copying or later publishing that file is what lets the provider test run meaningfully. Early in learning Pact it is common to run both sides from the same machine by hand, copying the pact file across, before introducing the broker that automates that handoff, which the exercises in this course follow in that order.
// consumer.pact.test.js
const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like } = MatchersV3;
const axios = require('axios');
const path = require('path');
const provider = new PactV3({
consumer: 'WebApp',
provider: 'UserService',
dir: path.resolve(process.cwd(), 'pacts'),
});
describe('User API contract', () => {
it('returns a user by id', async () => {
provider
.given('a user with id 42 exists')
.uponReceiving('a request for user 42')
.withRequest({
method: 'GET',
path: '/users/42',
})
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: {
id: like(42),
name: like('Ada Lovelace'),
email: like('ada@example.com'),
},
});
await provider.executeTest(async (mockServer) => {
const response = await axios.get(`${mockServer.url}/users/42`);
expect(response.status).toBe(200);
expect(response.data.name).toBe('Ada Lovelace');
});
});
});
A consumer test written with Jest and the Pact JavaScript client. It registers one interaction (a GET for user 42), starts an in-process mock server that behaves exactly as described, runs the application's HTTP call against that mock, and on success writes a pact file to the pacts directory describing the interaction.
// provider.pact.test.js
const { Verifier } = require('@pact-foundation/pact');
const path = require('path');
const { startServer, stopServer } = require('./testServer');
describe('User Service provider verification', () => {
let server;
beforeAll(async () => {
server = await startServer({ port: 8081 });
});
afterAll(async () => {
await stopServer(server);
});
it('satisfies the WebApp contract', () => {
return new Verifier({
provider: 'UserService',
providerBaseUrl: 'http://localhost:8081',
pactUrls: [path.resolve(process.cwd(), 'pacts', 'webapp-userservice.json')],
stateHandlers: {
'a user with id 42 exists': async () => {
// seed the test server's in-memory store
return Promise.resolve();
},
},
}).verifyProvider();
});
});
A provider verification test. It starts the real provider service on a local port, points the Pact Verifier at the pact file produced by the consumer test, and for each interaction runs any matching state handler (to put the provider into the state the interaction assumes, such as 'a user with id 42 exists') before replaying the recorded request and checking the real response.
Tips
- Write the consumer test the same way you would write any test for the code that calls the API: start from what the application actually needs from the response, not from what you imagine the provider returns, so the contract reflects real consumer behaviour.
- Use matchers like 'type' or 'regex' instead of exact values for fields such as ids, timestamps or generated tokens, so the contract does not break on every run just because a value changed but its shape did not.
- Run the consumer and provider tests locally, by hand, before introducing a broker or CI; understanding the two tests and the file that passes between them makes the later automation much easier to reason about.
- Name each interaction's provider state clearly (for example 'a user with id 42 exists') because that string is what the provider's state handler matches on to set up its data before replaying the request.
Common pitfalls
- Writing the consumer test against the real provider's actual current response instead of what the consumer logically needs: this makes contracts brittle and tends to encode incidental details (field order, extra fields) as if they mattered. Fix this by asserting only on the fields and shapes the consumer code actually reads.
- Forgetting that the provider verification test needs a running, real instance of the provider's code, not a mock of it: a common early mistake is to verify against a hand-written stub, which proves nothing about the real service. Always point the Verifier at the actual service, even if it is a lightweight in-memory version for the test.
- Treating a passing consumer test as proof the integration works: a consumer test only proves the consumer's code handles the responses it assumes it will get. The contract is only trustworthy once the provider verification has also passed against the same file.
Writing Consumer Tests and Generating Contracts
Once a consumer test suite can produce a basic pact file, the real work begins: writing tests that capture what the consumer genuinely depends on, no more and no less. A pact file is not a general-purpose API spec; it is a record of specific interactions the consumer actually exercises. This section covers the techniques that keep contracts realistic and useful: provider states that set up the data a given interaction needs, matching rules that assert on structure and type rather than brittle exact values, and patterns for organizing multiple interactions, error responses and edge cases in a single test file.
A well-written consumer test describes three things clearly: the state the provider must be in before the request is made, the request itself (method, path, headers, body), and the expected response shape. Pact frameworks such as Pact JS, pact-python and pact-jvm all follow this same three-part structure, even though the syntax differs. Keeping each interaction focused on a single scenario, rather than bundling many assertions into one giant test, makes the resulting pact file easier for a provider team to read and verify.
What this section covers
- Writing provider states with the setup data an interaction requires
- Using matching rules (type, regex, array-like) instead of hardcoded values
- Structuring a test file with multiple interactions cleanly
- Testing 4xx and 5xx responses as first-class interactions
- Keeping the generated pact file minimal and faithful to real consumer needs
By the end of this section, you should be able to look at a generated pact file and recognize every interaction in it as something your consumer code actually does, not a speculative guess at what the API might support.
Provider States and Matching Rules
A provider state is a named precondition, such as "a product with ID 42 exists", that tells the provider what data to set up before it replays an interaction during verification. Without a provider state, the provider has no way to know that an order with a given ID should exist when the consumer test expects a 200 response for it. States should be described in plain, specific language and should carry only the parameters the interaction needs, for example { productId: 42 }, so the provider's state-handling code can seed exactly that record.
Matching rules are what keep contracts flexible without becoming meaningless. If a consumer test asserts an exact timestamp or a specific UUID, the contract becomes brittle: it will fail verification the moment the provider generates a different real value, even though the shape of the response is correct. Instead, use type matchers (assert the field is a string, a number, a boolean), regex matchers for fields with a known pattern (an ISO date, a postcode), and array-like matchers (eachLike) to say "the response is an array where every item looks like this example," rather than asserting a fixed array length.
A common pitfall is being too loose: asserting only anything() everywhere makes the contract useless as documentation. The goal is matching rules that are as strict as the consumer's real logic requires, for example asserting a status field is one of a known enum, while being loose about values the consumer never inspects, such as internal database IDs the consumer only passes through.
Organizing Multiple Interactions and Error Cases
A single consumer test file typically needs several interactions: the happy path, one or more error responses the consumer's code actually handles, and sometimes edge cases like an empty list or a paginated second page. Each interaction should be added separately and verified independently so that a failure clearly points to one specific scenario rather than a tangle of overlapping requests.
Error responses deserve the same care as success responses. If the consumer has a branch of code that reacts to a 404 (show a "not found" message) or a 422 (show validation errors from a particular field), that behavior should be backed by its own interaction with its own provider state, such as "no product exists with ID 999". Skipping error cases is one of the most common gaps in consumer-driven contracts: the happy path gets tested thoroughly, but the moment the provider changes its error payload shape, nothing catches it until production.
When interactions start to pile up, split them across logically named test files or group them by the consumer behavior under test, rather than by HTTP endpoint. A test file organized around "what happens when checkout fails" is more maintainable than one organized around "POST /orders" that mixes unrelated success and failure concerns. Finally, review the generated pact file after adding new interactions and prune any left over from earlier refactors; an unused interaction makes the provider verify behavior that no consumer code depends on anymore, which wastes verification time and confuses anyone reading the contract later.
const { Matchers } = require('@pact-foundation/pact');
const { like, eachLike, term } = Matchers;
describe('Product API consumer', () => {
it('returns a product when it exists', () => {
return provider
.given('a product with ID 42 exists')
.uponReceiving('a request for product 42')
.withRequest({ method: 'GET', path: '/products/42' })
.willRespondWith({
status: 200,
body: like({
id: 42,
name: 'Desk Lamp',
price: 29.99,
tags: eachLike('office'),
createdAt: term({
matcher: '\\d{4}-\\d{2}-\\d{2}',
generate: '2024-01-15'
})
})
})
.then(() => client.getProduct(42));
});
it('returns 404 when product does not exist', () => {
return provider
.given('no product exists with ID 999')
.uponReceiving('a request for a missing product')
.withRequest({ method: 'GET', path: '/products/999' })
.willRespondWith({ status: 404, body: like({ error: 'Not found' }) })
.then(() => client.getProduct(999).catch(e => expect(e.status).toBe(404)));
});
});
A consumer test file using Pact JS that defines two interactions: a success case with type and array matching rules plus a regex-matched date, and a 404 error case backed by its own provider state, both verified against a mock provider.
Tips
- Name provider states specifically enough that a provider developer can write the exact setup code without guessing, such as "a user with email a@test.com exists and is locked" rather than "a user exists"
- Prefer eachLike and type matchers over hardcoded sample values for any field whose exact content the consumer does not check
- Write one interaction per distinct consumer behavior, including error branches, rather than one giant interaction that covers every field the API happens to return
Common pitfalls
- Asserting exact values (timestamps, generated IDs) instead of matchers, which makes the contract fail verification whenever the provider produces a different but equally valid real value
- Only testing the happy path and skipping error responses the consumer code actually handles, leaving a gap where a changed error payload shape breaks production silently
Provider Verification, the Pact Broker, and CI
Once a consumer has generated a pact file describing its expectations of a provider, that contract needs to be verified against the real provider and shared with the rest of the team. This section covers the second half of the Pact workflow: pulling contracts down from a Pact Broker, running provider verification against them, publishing the results back, and using those results to decide whether a deployment is safe.
The Pact Broker (or a hosted equivalent like PactFlow) is the central hub that stores every pact file a consumer publishes, tagged by version and branch. A provider's CI pipeline fetches the latest relevant pacts from the broker, replays each interaction against a running instance of the provider (or against its code with test doubles for any dependencies), and asserts that the actual response matches what the consumer expected. The verification outcome, pass or fail, is then published back to the broker so it is visible to both teams.
This bidirectional flow is what makes Pact genuinely useful in a microservices setup: consumer teams and provider teams can work independently, yet the broker becomes the single source of truth for whether their services are still compatible. Skipping the 'publish back' step is a common mistake that silently breaks the whole safety net, because without published results the broker has no way to know a contract was ever checked.
The following subsections dig into the mechanics of verification and into can-i-deploy, the command that turns all of this into an automated release gate.
Running and Publishing Provider Verification
Provider verification is typically written with a Pact provider verifier library for your language (for example pact-jvm-provider-junit5, pact-provider-verifier for Ruby, or the JS @pact-foundation/pact provider verifier). You point the verifier at your broker URL, your provider name, and the state-handler functions that set up any preconditions a given interaction needs (an existing user, an empty cart, and so on).
A typical verification run does the following: fetch pacts tagged for the current environment or branch, stand up the provider (often in-process or against a test database), replay each recorded request, compare the actual response against the expected one, and report pass/fail per interaction. Verification results are published automatically when you set publishVerificationResult: true and supply the provider's version (usually the git SHA).
Tagging matters a great deal here. Consumers publish pacts tagged with their branch or environment (main, staging), and providers verify only the tags relevant to where they are about to deploy. Without consistent tagging, a provider might verify against a stale or irrelevant contract version, giving false confidence.
For contracts that represent not-yet-agreed or evolving behaviour, Pact supports pending pacts (new interactions from the consumer that do not yet fail the provider's build, giving the provider team time to implement them) and WIP pacts (work-in-progress pacts included in verification reporting without blocking deployment). Both features let teams introduce breaking or new contracts gradually instead of freezing all deployments the moment a consumer's expectations change.
can-i-deploy and CI Integration
can-i-deploy is the command that queries the broker and answers one question: is it safe for this version of this service to go to this environment, given everything that has been verified so far? It checks, for every pact involving the service, whether a successful verification exists between the specific consumer and provider versions in play. If any required pact has not been verified, or was verified and failed, can-i-deploy exits non-zero and the deployment pipeline should stop.
Wiring this into CI typically means two separate pipelines. The consumer pipeline runs consumer tests, publishes the resulting pact file to the broker with its version and branch tag, then calls can-i-deploy before deploying to confirm the provider already supports it. The provider pipeline fetches pacts, runs verification, publishes results, then also calls can-i-deploy before its own deployment.
A practical tip is to use the broker's webhooks to trigger the provider's verification pipeline automatically whenever a consumer publishes a new pact, rather than relying on a schedule, so contract drift is caught within minutes rather than at the next nightly build. Keep provider and consumer version numbers meaningful (git SHAs are ideal) since can-i-deploy reasons entirely in terms of version compatibility, not dates or branch names alone.
# In the provider's CI pipeline, after running verification and publishing results
pact-broker can-i-deploy \
--pacticipant OrderService \
--version $(git rev-parse HEAD) \
--to-environment production \
--broker-base-url https://broker.example.com \
--broker-token $PACT_BROKER_TOKEN
Checks whether the current provider build can safely be deployed to production by confirming every relevant consumer contract has already been verified successfully.
const { Verifier } = require('@pact-foundation/pact');
new Verifier({
provider: 'OrderService',
providerBaseUrl: 'http://localhost:8080',
pactBrokerUrl: 'https://broker.example.com',
pactBrokerToken: process.env.PACT_BROKER_TOKEN,
publishVerificationResult: true,
providerVersion: process.env.GIT_SHA,
consumerVersionSelectors: [{ mainBranch: true }, { deployedOrReleased: true }],
stateHandlers: {
'an order exists': () => seedOrder()
}
}).verifyProvider().then(() => console.log('Verification complete'));
Runs provider verification against pacts fetched from the broker for the consumer's main branch and any currently deployed versions, then publishes the pass/fail result back under the provider's git SHA.
Tips
- Always version providers and consumers with something traceable like a git SHA, since can-i-deploy compatibility checks depend entirely on matching those versions correctly.
- Use consumer version selectors (mainBranch, deployedOrReleased) rather than verifying every pact ever published, so verification stays fast and relevant to what is actually in production.
- Set up broker webhooks so a new consumer pact automatically triggers the provider's verification build instead of waiting for the next scheduled run.
Common pitfalls
- Forgetting to set publishVerificationResult to true: verification runs locally and passes, but the broker never learns about it, so can-i-deploy later blocks a perfectly safe deployment.
- Treating pending or WIP pacts as optional busywork and ignoring their failures entirely, which lets a provider silently fall out of sync with a consumer's genuinely required new behaviour.
Exercises
Exercise 1: Your First Consumer Contract
In this exercise you will write a consumer test for a small client that fetches a product by id from a product service, run it to generate a pact file, and inspect the resulting JSON to understand exactly what Pact recorded. The goal is not to make the test clever, but to see the full cycle from test code to contract file with your own hands, and to connect each part of the test you write to the matching part of the pact file it produces. You will start with a simple HTTP client function in the language of your choice (JavaScript, Python or Java are all fine, pick whichever you are most comfortable testing in), write a Pact consumer test around it that describes one interaction, run the test, and then open the generated pact file in a text editor to read through it line by line, matching each part back to the test code that produced it. Pay particular attention to how a matcher you used in the test (for example 'like' for a type match) appears in the pact file's matching rules section, separately from the example value itself.
- Set up a small project with a Pact consumer library for your chosen language and a basic HTTP client function that calls GET /products/{id}
- Write a consumer test that registers an interaction for 'a product with id 7 exists', expecting a 200 response with a product object containing id, name and price
- Use a type matcher for id and price, and an exact or type matcher for name, explaining in a comment why you chose each
- Run the test and confirm it passes, producing a pact file in your output directory
- Open the pact file and identify the request, the response, and the matchingRules section, and write a short note mapping each back to a line in your test
Expected outcome: A passing consumer test and a generated pact file whose interactions, request, response and matching rules you can explain line by line, demonstrating that you understand what a consumer test actually produces and why.
Exercise 2: Verifying the Contract Against a Real Provider
Building on Exercise 1, you will now write the provider side: a small real service that implements GET /products/{id}, and a Pact provider verification test that replays the pact file from Exercise 1 against it. You will deliberately introduce a mismatch (for example, naming the field differently or omitting price) to see a verification failure, then fix the provider so verification passes, to understand what a real contract break looks like in test output and how to read it.
- Write a minimal real service (no mocking) that responds to GET /products/{id} with a hard-coded or in-memory product object
- Write a Pact provider verification test that points at the pact file from Exercise 1 and includes a state handler for 'a product with id 7 exists' that seeds your service's data
- Run verification and confirm it passes against a correctly implemented service
- Rename or remove a field in the provider's response and re-run verification, reading the failure output carefully
- Fix the provider so the field matches again and confirm verification passes a second time
Expected outcome: A working provider verification test that passes against a correct implementation and fails with a clear, readable diff when the provider's response no longer matches the contract, demonstrating the value of provider verification in catching breaking changes.
Quiz
1. What is the primary advantage of contract testing over full end-to-end testing when checking that two services agree on an API's shape?
- Contract testing checks performance under load, which end-to-end tests cannot
- Contract testing lets each side be tested independently, without running the whole system together, while still catching real integration breaks
- Contract testing replaces the need for any provider-side testing entirely
- Contract testing automatically generates the provider's implementation code
Show answer
B. Contract testing lets each side be tested independently, without running the whole system together, while still catching real integration breaks
Contract testing narrows the question from 'does the whole system work together' to 'does this provider still honour what this consumer needs', which can be checked on each side independently, without deploying every dependency together as end-to-end testing requires.
2. In Pact's consumer-driven model, which side's test produces the pact file (the contract)?
- The provider's test, because it owns the real implementation
- The Pact Broker, by inspecting both sides' code
- The consumer's test, by running against a mock provider that records each interaction
- A separate specification document written before any code
Show answer
C. The consumer's test, by running against a mock provider that records each interaction
In Pact, the consumer writes a test describing the requests it sends and the responses it needs; running that test against Pact's mock server records each interaction and writes the resulting pact file. The provider never writes the contract, it only verifies it.
3. What does a provider verification test actually run against?
- A mock of the provider, built from the pact file itself
- The real, running provider application code, replaying each recorded request from the pact file
- A copy of the consumer's test suite
- The provider's API documentation, to check it is complete
Show answer
B. The real, running provider application code, replaying each recorded request from the pact file
Provider verification is meaningful precisely because it runs against the real provider implementation, not a mock. Each interaction's request from the pact file is replayed against the live service, and the real response is checked against what the consumer's test expected.
4. Why would a consumer test use a type matcher (such as matching 'any integer') instead of an exact value for a field like a generated user id?
- Type matchers make the test run faster
- Exact values are not supported by Pact at all
- A type matcher asserts on the shape the consumer actually depends on, so the contract does not break every time an incidental value such as a generated id changes
- Type matchers are required for every field in a pact file
Show answer
C. A type matcher asserts on the shape the consumer actually depends on, so the contract does not break every time an incidental value such as a generated id changes
Using a matcher instead of an exact value keeps the contract focused on what the consumer truly needs (a field of a given type or format), avoiding false failures when a value that does not matter to the consumer, like a generated id or timestamp, simply changes between runs.
5. What role does a Pact Broker play once a team moves beyond running consumer and provider tests by hand on one machine?
- It writes the provider's implementation automatically based on the contract
- It stores pact files and verification results so either side can query whether it is safe to deploy, and automates handing the contract from consumer to provider builds
- It replaces the need for a provider verification test
- It is only needed for performance testing, not contract testing
Show answer
B. It stores pact files and verification results so either side can query whether it is safe to deploy, and automates handing the contract from consumer to provider builds
The Pact Broker is a shared service that stores published pact files and the results of provider verification against them. It lets a CI pipeline check, for any pair of consumer and provider versions, whether verification has passed, which is what a can-i-deploy style check relies on.