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

📚 Interview question

You are the senior engineer on a new .NET 10 service: an orders API on Azure that publishes events to Service Bus and calls a payment provider. Design its test strategy. Which test types do you use and roughly how many, where does each run, what blocks a merge or a release, and how will you know the strategy is working?

Designing a test strategy for a new .NET 10 service: choosing test types by risk, the shape and size of each layer, where each runs in CI/CD, merge and release gates, ownership, and the metrics that show whether the strategy works.

Senior Architecture Advanced architecture ci-cd contract-testing integration-testing test-strategy testing

🎯 Key points

  • Start from risks (money, data, contracts, availability), not from a pyramid diagram
  • Unit tests for domain rules; integration tests per endpoint and handler with WebApplicationFactory, SQL Server in Testcontainers and the Service Bus emulator or a fake publisher
  • Test the transactional outbox you implement (order row and outbox row in one SaveChanges) and idempotent consumers (same message twice, one side effect)
  • Contract tests for published events and the payment provider boundary (Verify snapshots, Pact, WireMock.Net stubs with faults)
  • Thin E2E and smoke tests after each deployment; load, stress and soak tests (k6 or Azure Load Testing) before launch and peaks
  • Merge gate: build, analysers, unit, integration, contract, under ~10 minutes; release gate: smoke and critical E2E on a staging slot
  • Continue after release: production smoke tests, SLO alerts in Application Insights, nightly sandbox and reduced load runs
  • Measure: escaped defects, change failure rate, PR feedback time, flaky-test rate, mutation score on core rules; record it all in a test strategy ADR

⏱ 30-second answer

I'd start from the risks, not a pyramid: wrong money (pricing, payment), lost or duplicated orders, broken contracts with event consumers and the payment provider, and availability at peak. Then match each risk to the cheapest test that catches it. Unit tests for domain rules, integration tests for every endpoint and message handler using WebApplicationFactory, SQL Server in Testcontainers and a Service Bus emulator or fake, contract tests for published events and the payment API, a thin layer of smoke and E2E tests after each deployment, and load tests before launch. The merge gate is fast (under ~10 minutes); the release gate is smoke plus critical E2E on a staging slot. I judge it by escaped defects, change failure rate and feedback time. The trade-off is up-front effort in fixtures and contracts for much cheaper changes later.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start by listing what would actually hurt: charging the wrong amount, losing or double-processing an order, publishing an event that breaks a downstream consumer, a payment provider change we don't notice, and falling over at peak. The test strategy is just a mapping from each of those risks to the cheapest test that would catch it, plus where that test runs and what it blocks.

For example, at [company] we built [a similar service] and I set it up like this. Pricing, discounts and order state transitions are pure domain code with a few hundred unit tests that run in seconds. Every endpoint and every Service Bus handler gets integration tests through WebApplicationFactory, with SQL Server in Testcontainers and Respawn between tests, the payment provider stubbed with WireMock.Net including declines and timeouts, and the outbox checked so an order and its event commit together. The events we publish have contract tests: a schema snapshot with Verify and, where consumers are internal, Pact so they can tell us what they rely on. That runs on every PR in about [eight] minutes and blocks the merge. After deployment to a staging slot, smoke tests and five critical E2E journeys run before the slot swap; smoke runs again in production with automatic swap-back. Before launch and before [end of financial year], a load and soak test. [Result: e.g. change failure rate under 5% over the first six months.]

The mistake I see is copying a ratio like 70/20/10 without asking what this service's risks are, or creating a separate QA phase that turns regression into a two-week hand-off. I'd write the strategy as a one-page ADR, have the team own all of it, and review it after every incident: if a bug escaped, which test should have caught it, and why didn't we have it?"


Risk to test mapping

Risk Test that catches it cheapest Runs Blocks
Wrong price, discount or GST Unit tests with boundary values; Stryker.NET on the domain project PR Merge
Endpoint wiring, validation, authorisation WebApplicationFactory integration tests PR Merge
EF Core queries, migrations, constraints Integration tests on SQL Server (Testcontainers) PR Merge
Order saved but event lost / duplicated Integration test of outbox + idempotent handler PR Merge
Breaking an event consumer Contract tests (schema snapshot, Pact) PR, plus provider verification Merge
Payment provider behaviour WireMock.Net stubs incl. faults; sandbox check nightly PR / nightly Merge / alert
Bad config, identity, Key Vault access Smoke tests on staging slot and production After deploy Slot swap / rollback
Critical user journeys 3–5 E2E tests After deploy to staging Release
Capacity at peak, leaks Load, stress, soak tests Pre-launch, pre-peak, nightly reduced Go-live

Rough shape for this service

Layer Count (order of magnitude) Time
Unit 300–800 < 30 s
Integration (API + handlers) 80–200 2–6 min, parallel collections
Contract 10–30 < 1 min
E2E 3–8 2–5 min post-deploy
Smoke 5–10 checks < 1 min

Gates

 PR:       build -> analysers -> unit -> integration -> contract   (target < 10 min)  => merge
 main:     build once -> image -> deploy staging slot -> smoke -> E2E          => swap
 prod:     smoke -> auto swap-back on failure
 nightly:  full Stryker, payment sandbox check, reduced load test vs baseline   => alert

Production example

On a service set up this way, the PR gate ran 540 tests in about 7 minutes. In the first six months, 3 of roughly 160 deployments needed a rollback (under 2%), and each incident review added one missing test, two of them contract tests for event fields a consumer had started depending on.

🔍 What the interviewer is checking

Checks whether the candidate can design a test strategy from risks and delivery constraints, and own its outcomes.

Green flags

  • Starts from risks and boundaries, not a ratio.
  • Clear placement of each test type and what it blocks.
  • Covers messaging (outbox, idempotency) and contracts.
  • Fast merge gate with slower checks moved later, not dropped.
  • Outcome metrics and a feedback loop from incidents.

Red flags

  • "We'll aim for 80% coverage" as the whole strategy.
  • Relies on a manual QA phase or a large E2E suite.
  • No idea how long the PR gate takes or should take.

📚 Learn in depth

1. Strategy is a set of decisions, not a diagram

A test strategy answers five questions:

  1. What risks matter for this system?
  2. Which test type catches each one most cheaply?
  3. Where does each run (PR, main, post-deploy, nightly)?
  4. What does a failure block (merge, release, nothing but an alert)?
  5. How do we know it is working?

The pyramid (many unit, fewer integration, few E2E) and the trophy (integration-heavy) are heuristics for question 2. For an API whose main logic is orchestration and data access, the integration layer is usually the thickest.

2. The feedback loop budget

 developer change
   | seconds    unit tests in IDE / dotnet watch test
   | minutes    PR gate (unit + integration + contract)  <-- keep under ~10 min
   | ~30 min    deploy to staging, smoke, E2E
   | hours      nightly: mutation, load, sandbox checks
   v
 production   smoke, alerts, SLOs

Every check you move earlier is cheaper to act on. Every check you add to the PR gate costs every developer every PR, so the PR gate is reserved for fast, deterministic tests.

3. Testing the messaging parts

  • Outbox: an integration test that saves an order and asserts both the row and the outbox message exist in the same transaction; a second test that the dispatcher publishes it.
  • Idempotent consumers: deliver the same message twice and assert one side effect.
  • Broker: the Azure Service Bus emulator (a container) for tests that depend on sessions, dead-lettering or lock renewal; a fake publisher for tests that only care that a message was sent.

4. Contracts at both edges

  • Outbound events: snapshot the serialised JSON with Verify so any change is a visible diff in the PR; for internal consumers, consumer-driven contracts (Pact) so you know what they actually read.
  • Inbound payment API: WireMock.Net stubs built from the provider's documented examples, and a nightly test against the provider's sandbox to detect drift.

5. Ownership and the ADR

The team that writes the code writes and maintains the tests; testers, where present, focus on exploratory testing and on helping design test cases, not on manual regression. A one-page ADR records the risk map, gates and targets so new team members don't re-argue it.

6. Measuring the strategy

Metric Target example Source
Escaped defects Trending down Incident and bug tracker
Change failure rate (DORA) < 10% Deployment and rollback records
PR feedback time < 10 min p90 CI analytics
Flaky-test rate < 1% of runs CI retry / quarantine reports
Mutation score (domain) > 75% Stryker.NET

Try it yourself

  1. Write the risk-to-test table for a service you know; mark gaps.
  2. Measure your current PR gate time and list the three slowest test classes.
  3. Add a JSON snapshot test (Verify) for one published event.
  4. Write an integration test that sends the same message twice to a handler and asserts one side effect.
  5. Draft a one-page test strategy ADR and review it with your team.

💻 Code

Two tests that cover the riskiest boundaries of the orders service: the outbox and the published event contract.

namespace Orders.Tests.Integration;

using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Orders.Data;
using Xunit;

[Collection("api")]
public sealed class PlaceOrderTests(ApiFixture fixture) : IAsyncLifetime
{
    public async ValueTask InitializeAsync() => await fixture.ResetAsync();
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;

    [Fact]
    public async Task Placing_an_order_saves_it_and_its_event_atomically()
    {
        var ct = TestContext.Current.CancellationToken;
        var client = fixture.CreateAuthenticatedClient(role: "Customer");

        var response = await client.PostAsJsonAsync("/orders",
            new { productId = "SKU-1", quantity = 2 }, ct);

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);

        using var scope = fixture.Factory.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
        var order = await db.Orders.SingleAsync(ct);
        var outbox = await db.OutboxMessages.SingleAsync(ct);

        // The event is written in the same transaction as the order (outbox pattern).
        Assert.Equal("OrderPlaced", outbox.Type);
        Assert.Contains(order.Id.ToString(), outbox.Payload);
    }
}
namespace Orders.Tests.Contracts;

using System.Text.Json;
using Orders.Contracts;
using VerifyXunit;
using Xunit;

public sealed class OrderPlacedContractTests
{
    [Fact]
    public Task OrderPlaced_event_shape_is_stable()
    {
        var evt = new OrderPlaced(
            OrderId: Guid.Parse("7d0f8a8e-3b1c-4f7e-9a51-1b6a2a0f9c11"),
            CustomerId: "cust-42",
            Total: 135.00m,
            Currency: "AUD",
            PlacedAtUtc: new DateTimeOffset(2026, 7, 1, 9, 30, 0, TimeSpan.Zero));

        // Any change to field names, types or casing shows up as a diff in the PR.
        var json = JsonSerializer.Serialize(evt, JsonSerializerOptions.Web);
        return VerifyJson(json);
    }
}
# PR gate in GitHub Actions: fast and deterministic tests only
- run: dotnet build -c Release
- run: dotnet test tests/Orders.Tests.Unit --no-build -c Release
- run: dotnet test tests/Orders.Tests.Integration --no-build -c Release
- run: dotnet test tests/Orders.Tests.Contracts --no-build -c Release

⚠ Common mistakes

  • Mistake: Copying a fixed ratio (70/20/10) without looking at the service's risks. Why it is wrong: an orchestration-heavy API gets thousands of trivial unit tests and no tests of its real boundaries. Instead: map risks to the cheapest test that catches each.
  • Mistake: Putting slow or non-deterministic tests in the PR gate. Why it is wrong: feedback slows, flakiness rises, and developers start bypassing the gate. Instead: keep the PR gate fast and deterministic; move E2E, load and sandbox checks later.
  • Mistake: Ignoring contracts for published events. Why it is wrong: a renamed field breaks consumers that you never run in your tests. Instead: schema snapshots and consumer-driven contracts.
  • Mistake: A separate QA phase for regression. Why it is wrong: weeks of delay and a team that doesn't own quality. Instead: automated regression owned by the delivery team; testers do exploratory work.
  • Mistake: No post-deployment checks. Why it is wrong: configuration and identity failures only show in a real environment. Instead: smoke tests gating slot swaps, with automatic rollback.
  • Mistake: Not measuring the strategy. Why it is wrong: you can't tell whether extra tests are reducing incidents. Instead: track escaped defects, change failure rate, feedback time and flaky rate.
  • Mistake: Never revisiting the strategy. Why it is wrong: the system's risks change. Instead: every incident review asks which test should have caught it.

🏛 Senior insight: trade-offs

A test strategy is an architecture decision: it shapes how fast the team can change the system safely. The senior move is to make it explicit and risk-driven, keep the merge gate fast enough that nobody wants to bypass it, push slow checks to later stages without dropping them, and tie the whole thing to outcome metrics rather than coverage. For a messaging service, the boundaries (database, outbox, broker, external APIs, event contracts) are where most production incidents start, so that is where the integration and contract investment goes.

Option When it fits Cost When not to
Unit-heavy pyramid Rich domain logic, few boundaries Low per test Thin orchestration APIs
Integration-heavy (trophy) APIs, handlers, data access Medium; needs good fixtures CPU-bound libraries
Consumer-driven contracts (Pact) Several internal consumers, independent deploys Broker plus team discipline One consumer owned by the same team
Large E2E suite Rarely; regulated sign-off journeys High, flaky As the main safety net

Measure it with DORA change failure rate, escaped defects per release and PR feedback time; if all three are moving the right way, the strategy is working.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions unit, integration and E2E layers. Why: Checks the candidate's fundamentals on what each test level proves.
    How to answer

    A unit test checks one piece of behaviour in memory with no I/O: a pricing rule, a validator, a domain method. It runs in milliseconds and tells you exactly which logic broke. An integration test checks that real parts work together: the ASP.NET Core pipeline, routing, model binding, EF Core against a real SQL Server. It takes seconds and catches wiring, mapping and SQL mistakes that unit tests can't see. An end-to-end test drives the deployed system the way a user does, through a browser or the public API, and proves a whole journey works.

    The trade-off: as you move from unit to E2E, each test gives more confidence that the real thing works but is slower, flakier and worse at saying where the problem is.

  2. When: Candidate mentions contract tests for events or the payment provider. Why: Checks the candidate can justify contract tests over end-to-end tests between services.
    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.

  3. When: Candidate mentions breaking changes or API contracts. Why: Checks how the candidate protects the HTTP API contract in CI.
    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.

🛠 Real-world problems: how you handle them

Replacing a two-week manual regression phase with a risk-based strategy
Situation
A [retail] team released an orders API [monthly] after a two-week manual regression phase run by [two] testers. Releases still caused [one or two] P2 incidents each, mostly around events consumed by the warehouse system and payment edge cases.
Signals
Change failure rate around [30%]; lead time from merge to production over three weeks; incident reviews repeatedly citing "not covered by regression checklist"; CI had unit tests only, about [4] minutes.
Investigation
Classified the last [12] incidents by root cause: 5 event contract changes, 3 EF Core query or migration issues, 2 payment provider edge cases, 2 configuration. Checked CI test reports: no test touched SQL Server, Service Bus or the payment client. Interviewed the warehouse team about which event fields they read.
Resolution
Immediate: added Verify snapshots for all published events and WireMock.Net tests for payment declines and timeouts, which caught a breaking change the same week. Then built a `WebApplicationFactory` + Testcontainers integration suite for every endpoint and handler, added outbox and idempotency tests, smoke tests gating slot swaps, and five E2E journeys. Testers moved to exploratory testing and test design.
Prevention
Test strategy ADR with the risk map and gates; incident review template asks which test should have caught it; dashboard of change failure rate, PR feedback time and flaky-test rate; consumer-driven contracts with the warehouse team.

How to tell it (STAR)

**S:** Our orders API went through a two-week manual regression phase every release and still caused [one or two] incidents. **T:** I was asked to make releases safer and faster. **A:** I grouped the last [12] incidents by cause and found most were event contracts, data access and payment edge cases that our unit tests never touched. I proposed a risk-based strategy: integration tests on real SQL Server for every endpoint and handler, contract snapshots for events, WireMock.Net for payment faults, and smoke tests gating slot swaps. We wrote it up as an ADR and the testers moved to exploratory work. **R:** We went from [monthly] to [weekly] releases, the PR gate stayed under [eight] minutes, and change failure rate dropped from about [30%] to [under 10%] over [two quarters].

↩ Usually asked after

More in Test Types

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me