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.
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.
"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 | 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 |
| 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 |
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
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.
Checks whether the candidate can design a test strategy from risks and delivery constraints, and own its outcomes.
Green flags
Red flags
A test strategy answers five questions:
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.
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.
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.
| 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 |
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
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.
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.
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.
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].
Last updated 23 Nov 2026.