Consumer-driven contract testing in .NET with PactNet: writing consumer tests against the Pact mock server with matchers, verifying the provider against a real host with provider states, and using a Pact Broker, pending pacts and can-i-deploy to gate deployments.
In consumer-driven contract testing, the consumer writes tests that describe the requests it makes and the responses it needs. With PactNet, the consumer test runs the real HttpClient code against a Pact mock server; passing tests produce a pact file (JSON). The provider then verifies that file by replaying each interaction against its real API, with provider states (Given("payment 42 exists")) setting up data first. A Pact Broker (or PactFlow) stores pacts and results per version and branch, and can-i-deploy asks "is this version verified against what's in production?" before each release. Use matchers so the contract checks types and formats, not exact values. The trade-off: setup and provider-state upkeep, in exchange for catching breaking API changes in each service's own pipeline instead of in a slow, shared end-to-end environment.
"Contract testing answers one question: can these two versions talk to each other? End-to-end tests answer it too, but slowly, late, and in a shared environment that's always broken for some other reason. With Pact the consumer, say our web BFF calling a payments API, writes a test using its real typed
HttpClient. In the test I describe the interaction: given payment 42 exists, a GET to/payments/42returns 200 with an id, a status and an amount. PactNet starts a mock server, my client calls it, and if the client code works against that response the test passes and writes a pact file. I use matchers, so the contract says 'status is one of Pending, Settled or Failed' and 'amount is a decimal', not 'amount is exactly 10.50'. And I only include fields the consumer actually reads.On the provider side, the pact is replayed against the real API running on Kestrel, with its database or downstream calls faked underneath. Each interaction's provider state calls a state endpoint that seeds the data it needs. For example, at [company] we had [six] consumers of a [payments] API and a shared end-to-end environment that was red [a third] of the time. We published pacts to a broker, triggered provider verification by webhook when a pact changed, and added
can-i-deploybefore each deployment plusrecord-deploymentafter. Within [two months] we caught [three] breaking changes, like a renamed enum value, in the provider's PR build instead of in staging, and removed [most] of the end-to-end suite.The mistake I see is treating Pact as functional testing of the provider: asserting business rules in the contract and writing dozens of states. The contract should cover the shape and meaning of the interface the consumer depends on; the provider's logic is tested by the provider's own tests. Contracts are about compatibility, not correctness."
| Step | Who | Tooling |
|---|---|---|
| 1. Describe interactions, run client against mock | Consumer CI | PactNet Pact.V4(...).WithHttpInteractions() |
| 2. Publish pact with version and branch | Consumer CI | pact-broker publish (Pact CLI) |
| 3. Verify pact against the real provider | Provider CI (on its PRs and via webhook) | PactVerifier |
| 4. Publish verification result | Provider CI | PublishResults(...) |
| 5. Gate deployment | Both | pact-broker can-i-deploy --to-environment production |
| 6. Record what is deployed | Both | pact-broker record-deployment |
| Test | Proves | Speed | Owner |
|---|---|---|---|
| Consumer unit tests | Client logic | ms | Consumer |
| Consumer Pact test | Client works with the agreed response shape | ms–s | Consumer |
| Provider verification | Provider still honours every consumer's pact | seconds | Provider |
| Provider functional tests | Business rules | seconds | Provider |
| End-to-end | The deployed system works together | minutes | Shared |
| Fits | Doesn't fit |
|---|---|
| Several services owned by different teams, deployed independently | One team, one deployable |
| Internal APIs where consumers are known | Public APIs with unknown consumers (use OpenAPI diffing) |
| HTTP and message contracts (Service Bus, Kafka) | Pass-through proxies |
With [six] consumers of a payments API, provider verification ran in about [40] seconds per PR. After adoption, the shared end-to-end environment's role shrank to [a dozen] smoke journeys, and deployment lead time for the payments team fell from [two days] to [same day] because releases no longer waited on a full staging regression.
Checks whether the candidate can implement consumer-driven contract testing end to end and understands where it fits relative to functional and end-to-end tests.
Green flags
Red flags
Consumer A v12 ----\
Consumer B v7 -----+----> Provider v31 (deployed independently)
Consumer C v3 ----/
When services deploy independently, the question before each release is whether this version is compatible with the versions currently deployed. End-to-end environments answer it by deploying everything together, which couples teams and is slow and flaky. Contract tests answer it per pair, in each team's own pipeline.
Test ---> real PaymentsClient --HTTP--> Pact mock server (Rust core via PactNet)
| matches request against expectation
| returns the example response
Test asserts client result <-------------------+
On success: writes pacts/OrdersWeb-PaymentsApi.json
If the client sends a request the mock doesn't expect (wrong path, missing header), the mock returns an error and verification fails. Matchers in the pact (type, regex, integer, decimal, eachLike) mean the provider is later checked for compatible values, not identical ones.
The verifier reads each interaction, calls the provider-state endpoint with the state name (for example POST /provider-states {"state": "payment 42 exists"}), then sends the recorded request to the real provider and compares the response with the matchers. It needs a real HTTP endpoint, so an in-memory TestServer is not enough: start the app on Kestrel (in .NET 10, WebApplicationFactory can do this with UseKestrel()), and replace the database or downstream clients with fakes or a Testcontainers database.
States are the maintenance cost. Keep them few and descriptive ("payment 42 exists", "no payments for customer 7"), implement them by seeding an in-memory repository or test database, and reset between interactions. Too many states usually means the consumer is testing provider logic.
The broker stores each pact with the consumer version (git SHA) and branch, and each verification result with the provider version. Key features:
contract_requiring_verification_published).You can self-host the open-source Pact Broker (a container plus PostgreSQL) or use PactFlow (SmartBear, commercial).
Pact also covers asynchronous messages: the consumer test describes a message it can handle; the provider verification asks the provider to produce that message (through a message handler) and checks it. That is useful for Service Bus and Kafka contracts, where breaking changes are otherwise only found at runtime.
can-i-deploy.OrderPlaced event and verify it against the provider's message producer.Consumer test, provider verification and CI gate. PactNet 5.x API shown; check the PactNet README for the current version's exact method names.
// Consumer: OrdersWeb/PaymentsClient.cs
using System.Net.Http.Json;
namespace OrdersWeb;
public sealed record PaymentDto(int Id, string Status, decimal Amount);
public sealed class PaymentsClient(HttpClient http)
{
public Task<PaymentDto?> GetAsync(int id, CancellationToken ct) =>
http.GetFromJsonAsync<PaymentDto>($"/payments/{id}", ct);
}
// Consumer test: OrdersWeb.Tests/PaymentsClientPactTests.cs
using System.Net;
using OrdersWeb;
using PactNet;
using PactNet.Matchers;
using Xunit;
namespace OrdersWeb.Tests;
public sealed class PaymentsClientPactTests
{
private readonly IPactBuilderV4 _pact = Pact
.V4("OrdersWeb", "PaymentsApi", new PactConfig { PactDir = Path.Combine("..", "..", "..", "pacts") })
.WithHttpInteractions();
[Fact]
public async Task GetPayment_WhenItExists_ReturnsPayment()
{
_pact.UponReceiving("a request for an existing payment")
.Given("payment 42 exists")
.WithRequest(HttpMethod.Get, "/payments/42")
.WithHeader("Accept", "application/json")
.WillRespond()
.WithStatus(HttpStatusCode.OK)
.WithJsonBody(new
{
// Matchers: check type and format, only for fields this consumer reads.
id = Match.Integer(42),
status = Match.Regex("Settled", "^(Pending|Settled|Failed)$"),
amount = Match.Decimal(10.50m)
});
await _pact.VerifyAsync(async ctx =>
{
var http = new HttpClient { BaseAddress = ctx.MockServerUri };
http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
var payment = await new PaymentsClient(http).GetAsync(42, TestContext.Current.CancellationToken);
Assert.NotNull(payment);
Assert.Equal("Settled", payment.Status);
});
}
}
// Provider verification: PaymentsApi.Tests/PactVerificationTests.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using PactNet.Verifier;
using PaymentsApi;
using Xunit;
namespace PaymentsApi.Tests;
public sealed class PactVerificationTests
{
private static readonly Uri ProviderUri = new("http://localhost:9223");
[Fact]
public void Provider_HonoursAllConsumerPacts()
{
var payments = new InMemoryPaymentRepository();
using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(b =>
{
b.ConfigureTestServices(s =>
{
s.AddSingleton<IPaymentRepository>(payments); // fake below the API
s.AddSingleton<IStartupFilter>(new ProviderStateFilter(payments));
});
});
factory.UseKestrel(ProviderUri.Port); // .NET 10: real socket, which the Pact verifier needs
factory.StartServer();
using var verifier = new PactVerifier("PaymentsApi", new PactVerifierConfig());
verifier.WithHttpEndpoint(ProviderUri)
.WithFileSource(new FileInfo(Path.Combine("..", "..", "..", "..", "pacts", "OrdersWeb-PaymentsApi.json")))
// In CI, use the broker instead: .WithPactBrokerSource(brokerUri, o => o.TokenAuthentication(token)
// .ConsumerVersionSelectors(new ConsumerVersionSelector { MainBranch = true },
// new ConsumerVersionSelector { DeployedOrReleased = true })
// .EnablePending().PublishResults(gitSha, r => r.ProviderBranch(branch)))
.WithProviderStateUrl(new Uri(ProviderUri, "/provider-states"))
.Verify();
}
// Adds a test-only endpoint that the verifier calls before each interaction.
private sealed class ProviderStateFilter(InMemoryPaymentRepository payments) : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
{
app.Map("/provider-states", branch => branch.Run(async ctx =>
{
var body = await ctx.Request.ReadFromJsonAsync<ProviderState>();
payments.Clear();
if (body?.State == "payment 42 exists")
{
payments.Add(new Payment(42, PaymentStatus.Settled, 10.50m));
}
ctx.Response.StatusCode = StatusCodes.Status200OK;
}));
next(app);
};
}
private sealed record ProviderState(string State);
}
# CI gate before deploying either service, then record what went out.
pact-broker can-i-deploy --pacticipant PaymentsApi --version "$GIT_SHA" --to-environment production
# ... deploy ...
pact-broker record-deployment --pacticipant PaymentsApi --version "$GIT_SHA" --environment production
TestServer, or replacing the controller or API layer with a mock during verification. Why it is wrong: the Pact verifier is a separate process that needs a real network endpoint, and mocking the API layer means you verify the mock rather than the routing, serialisation and filters consumers actually hit. TestServer is still fine for the provider's own functional tests. Instead: run the real app on Kestrel and fake only dependencies below the API.can-i-deploy without record-deployment. Why it is wrong: the broker doesn't know what is in production, so the check is meaningless. Instead: record every deployment and release.Contract testing is as much an organisational tool as a technical one. It replaces "please tell us before you change the API" with a machine-checked list of exactly which consumers use which fields, and it moves the compatibility check into each team's pipeline. The payoff is independent deployment without a shared staging environment as the bottleneck. The cost is ongoing, and I'm explicit about it up front: someone owns the broker (hosting, upgrades, access tokens); teams agree on versioning (git SHA plus branch) and on recording every deployment; and provider states need care, kept few, coarse and reliable, so verification doesn't become a second, fragile test suite. I introduce it on the one or two most painful integrations first, including the events those services publish, not across 40 services at once.
I also keep the boundary clear with OpenAPI. Pact is consumer-driven and great for known internal consumers; OpenAPI diffing is provider-driven and suits public or partner APIs. Many organisations use both, or PactFlow's bi-directional mode to compare consumer pacts with the provider's OpenAPI document.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Pact (consumer-driven) | Internal services, known consumers, independent deploys | Broker, provider states, team buy-in | One team and one deployable |
| OpenAPI diff in CI | Public/partner APIs, provider-led change control | Low | When you need to know which consumer uses what |
| Bi-directional (PactFlow) | Consumers using Pact, provider with a reliable OpenAPI spec | Commercial tool | Spec not generated from code |
| Shared end-to-end environment | A few critical smoke journeys | Slow, flaky, coupled | As the main compatibility check |
I'd measure it by breaking changes caught pre-merge versus found in staging or production, and by deployment lead time.
A consumer-driven contract test checks one consumer-provider pair in isolation. The consumer's tests run against a Pact mock and record what it actually uses; the provider replays those expectations against its real code (dependencies stubbed) in its own CI. Because the provider must keep passing every consumer's contract, it can evolve and version its API without silently breaking anyone, which preserves team autonomy.
An end-to-end test deploys many services together and drives a real user journey. It catches wiring, configuration and infrastructure problems contract tests can't, but it needs a shared environment, runs for minutes, fails for unrelated reasons and slows every deployment pipeline that waits on it.
So: a contract test for every consumer-provider pair as the main safety net, and only a handful of end-to-end smoke tests for the few journeys that make money. The trade-off is fast, precise feedback versus realistic but slow, flaky coverage.
I make the committed build-time spec the contract and gate pull requests on it:
oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.
Use a Pact message (asynchronous) interaction. The consumer test describes the message it expects, with matchers for types and formats, and feeds it to its real handler, which must process it without error; that generates the pact, which acts as an executable schema for the fields the consumer relies on. The provider verification calls a message producer hook that builds the real message with the same serialiser and mapping code used in production, and checks it against the pact. The transport (Service Bus) is not part of the contract; the body and metadata (such as a type or version property) are. For evolution, add fields freely (consumers ignore unknown fields), never rename or remove a field a pact still uses, and introduce breaking changes as a new message type or version that runs alongside the old one until can-i-deploy shows no consumer needs it. Retries and dead-lettering are consumer behaviour, tested in the consumer's component tests, not in the contract.
How to tell it (STAR)
**S:** At [company], our [payments] API had six consumers and the only compatibility check was a shared staging environment that was red a third of the time. A renamed enum value broke three consumers and took two days to find. **T:** I was asked to stop breaking changes reaching staging without slowing teams down. **A:** I showed that every breaking change in six months was a shape or enum change, set up a Pact Broker, wrote the first consumer tests with the two biggest consumer teams, and added provider verification plus can-i-deploy and record-deployment to every pipeline. **R:** In the first [two months] we caught [three] breaking changes in the provider's PR build, staging shrank to a dozen smoke journeys, and the payments team went from [two-day] to [same-day] releases.
Last updated 23 Nov 2026.