📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How would you set up consumer-driven contract testing between two .NET services with Pact? Show a consumer test and provider verification, explain provider states, and how a Pact Broker and can-i-deploy fit into CI.

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.

Senior Coding Advanced aspnet-core ci-cd contract-testing microservices pact testing

🎯 Key points

  • Consumer-driven: the consumer's tests define the interactions it relies on; the pact file is generated, not hand-written
  • Consumer test runs real client code against the Pact mock server; matchers (type, regex) avoid over-specifying values
  • Only specify what the consumer uses; extra provider fields must not break the contract
  • Provider verification sends each recorded request to the real, running provider API and checks its actual responses against the pact's matchers; only the provider's own dependencies (database, downstream services) are faked
  • Provider states (Given) seed data via a state-change endpoint; keep them few and coarse, because they are the main maintenance cost
  • Message pacts cover async contracts (Service Bus, Kafka events) a provider produces, using its real serialisation code
  • Pact Broker / PactFlow stores pacts and results by version and branch; webhooks trigger verification; can-i-deploy plus record-deployment gate each release
  • Contract tests check the interface's shape and meaning, not the provider's business logic; they complement functional tests

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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/42 returns 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-deploy before each deployment plus record-deployment after. 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."


The flow

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

Contract vs other tests

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

When Pact fits

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

Production example

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.

🔍 What the interviewer is checking

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

  • Consumer test runs the real client against the Pact mock server; uses matchers; only consumed fields
  • Provider verification on a real host with dependencies faked below the API, and maintainable provider states
  • Broker with versions and branches, pending pacts, can-i-deploy plus record-deployment
  • Knows when OpenAPI diffing is the better tool

Red flags

  • Hand-written contract files or JSON schema shared by email
  • Business logic in the contract and dozens of provider states
  • Thinks contract tests replace all integration or end-to-end tests

📚 Learn in depth

1. The problem contract tests solve

   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.

2. Consumer-driven versus provider-driven

  • Consumer-driven (Pact): consumers state what they use; the provider proves it supports all of them. Providers learn exactly which fields are used, so they can safely remove unused ones.
  • Provider-driven / schema-based (OpenAPI diffing, bi-directional contract testing in PactFlow): the provider publishes a schema; consumers are checked against it. Better for public APIs or when consumers can't run Pact.

3. What the consumer test does

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.

4. What provider verification does

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.

5. Provider states

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.

6. The broker, versions and branches

The broker stores each pact with the consumer version (git SHA) and branch, and each verification result with the provider version. Key features:

  • Consumer version selectors: the provider verifies pacts from the consumers' main branch and from versions currently deployed or released, not every old version.
  • Pending pacts: a new consumer expectation doesn't fail the provider's build until the provider has verified it once, so consumers can't break the provider pipeline.
  • WIP pacts: the provider automatically verifies new feature-branch pacts too.
  • Webhooks: a changed pact triggers a provider verification build (contract_requiring_verification_published).
  • can-i-deploy + record-deployment: the deployment gate uses the matrix of verified pairs per environment.

You can self-host the open-source Pact Broker (a container plus PostgreSQL) or use PactFlow (SmartBear, commercial).

7. Messages

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.

Try it yourself

  1. Write a consumer test for one GET interaction with PactNet and inspect the generated JSON pact.
  2. Change the consumer to read a new field and watch the provider verification fail until the provider adds it.
  3. Replace an exact value with a regex matcher and remove a field the consumer doesn't read; see verification still pass.
  4. Run the Pact Broker container locally, publish a pact, verify it, and run can-i-deploy.
  5. Add a message pact for an OrderPlaced event and verify it against the provider's message producer.

💻 Code

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

⚠ Common mistakes

  • Mistake: Asserting exact values everywhere in the consumer pact. Why it is wrong: the provider fails verification over test data, not compatibility. Instead: use type and regex matchers; exact values only where they carry meaning (an enum the consumer switches on).
  • Mistake: Including every field the provider returns. Why it is wrong: the provider can never remove an unused field, and the contract stops showing what's really used. Instead: only fields the consumer reads.
  • Mistake: Writing provider business rules into the contract ("returns 422 when amount exceeds the daily limit for gold customers"). Why it is wrong: explodes provider states and duplicates the provider's own tests. Instead: contracts cover shape and key status codes; logic stays in provider tests.
  • Mistake: Creating a new provider state for every interaction. Why it is wrong: each state is setup code the provider team must maintain, and dozens of states usually mean the consumer is testing provider logic. Instead: a small set of coarse, reusable states ("payment 42 exists") seeded through one state endpoint.
  • Mistake: Verifying through 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.
  • Mistake: Sharing pact files by copying them between repositories. Why it is wrong: no versioning, no record of which versions are compatible. Instead: a Pact Broker or PactFlow with versions, branches and environments.
  • Mistake: Running 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.
  • Mistake: Letting new consumer expectations break the provider's main build. Why it is wrong: consumers can block provider releases for features not built yet. Instead: enable pending pacts and WIP pacts.
  • Mistake: Covering HTTP calls with pacts but leaving the events a service publishes uncovered. Why it is wrong: message contract breaks surface only at runtime, often as dead-lettered messages. Instead: message pacts for the events consumers depend on.
  • Mistake: Using Pact for a public API with unknown consumers. Why it is wrong: nobody writes consumer tests for you. Instead: OpenAPI breaking-change detection (for example oasdiff) and versioning.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares contract tests with end-to-end integration tests Why: Checks they can position contract testing within the overall test strategy at the architecture level.
    How to answer

    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.

  2. When: Candidate mentions OpenAPI or public APIs Why: Checks they know provider-driven breaking-change detection with OpenAPI in CI as the alternative.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: 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.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (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.

  3. When: Candidate mentions messaging or events between services Why: Checks they can extend contract testing beyond HTTP to the integrations that usually break silently.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Renamed enum value broke three consumers in staging
Situation
A [payments] API had [six] internal consumers owned by [four] teams, all deployed independently to Azure Container Apps in Australia East. Compatibility was checked only in a shared staging environment before release.
Signals
Staging was red about [a third] of the time; a provider change renaming `Completed` to `Settled` broke three consumers, found two days after merge; release trains were delayed while teams worked out whose change broke what.
Investigation
I mapped which consumers called which endpoints using Application Insights dependency telemetry and found most consumers used fewer than [half] the response fields. I listed the breaking changes from the previous [six months]: all were shape or enum changes that a contract test would have caught. I prototyped PactNet tests for the two biggest consumers.
Resolution
Immediate: restored `Completed` as an accepted alias and coordinated the rename properly. Long term: consumers published pacts to a self-hosted Pact Broker on each build; the provider verified main-branch and deployed pacts on every PR and via webhook; every pipeline ran `can-i-deploy` before deploying and `record-deployment` after. Provider verification took about [40] seconds.
Prevention
Pending and WIP pacts enabled so consumers can't break provider builds; a guideline on matchers and minimal fields; an ADR describing when to use Pact versus OpenAPI diffing; staging reduced to a dozen smoke journeys.

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.

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me