Covers the test pyramid, the testing trophy and the microservice honeycomb, and how to choose the mix of unit, integration and end-to-end tests for an ASP.NET Core API.
The test pyramid says: lots of fast unit tests at the bottom, fewer integration tests, and a handful of end-to-end tests at the top, because cost and flakiness rise as you go up.
The testing trophy keeps few end-to-end tests but makes integration tests the biggest layer, with static analysis underneath. The honeycomb says the same for microservices: test each service through its real boundaries.
For a CRUD-heavy ASP.NET Core API, most bugs live in wiring, SQL and serialisation, so I make integration tests with WebApplicationFactory and Testcontainers the bulk, and keep unit tests for real business rules. The trade-off: integration tests catch more real bugs but run slower and need infrastructure in CI.
"The pyramid came from Mike Cohn: a wide base of unit tests, a middle layer of service or integration tests, and a thin top of UI or end-to-end tests. The reasoning is economics. Unit tests run in microseconds and fail precisely; end-to-end tests take seconds or minutes, break for reasons unrelated to your change, and are hard to debug. So you push testing down as far as it can go.
The trophy, from Kent C. Dodds, and Spotify's honeycomb push back on that for modern services. If an endpoint mostly validates a request, runs an EF Core query and maps a result, a unit test with mocked
DbContextproves almost nothing, and the real bugs are a wrongInclude, a missing migration, a JSON casing change or a broken authorisation policy. Those only show up when the pieces run together. WithWebApplicationFactoryhosting the API in memory and Testcontainers running real SQL Server, an integration test takes tens of milliseconds once the container is up, so it can be the largest layer.So my answer is: the shape follows the risk. In a pricing or eligibility engine I write hundreds of unit tests because the logic is the risk. In a CRUD API, I'd aim for something like 60 to 70 percent integration tests through HTTP, unit tests for the domain rules, and five to ten end-to-end smoke tests after deployment. The mistake I see is teams chasing a pyramid shape by mocking repositories everywhere, which gives high unit coverage and still ships broken SQL. Pick the shape that catches your bugs at the lowest cost."
| Model | Biggest layer | Origin | Best fit |
|---|---|---|---|
| Pyramid | Unit | Mike Cohn, Succeeding with Agile (2009) | Logic-heavy code, libraries |
| Trophy | Integration | Kent C. Dodds (2018) | Apps and APIs where wiring is the risk |
| Honeycomb | Integrated tests per service | Spotify engineering (2018) | Microservices |
| Layer | Time per test | Failure precision | Flakiness |
|---|---|---|---|
| Unit | < 1 ms | Exact method | Very low |
| Integration (WAF + container) | 10β200 ms after startup | Endpoint or query | Low if isolated |
| End-to-end (deployed env, browser) | Secondsβminutes | Whole flow | Medium to high |
| Test type | Roughly | Covers |
|---|---|---|
| Unit | 30β40% | Pricing, discount and state-transition rules |
| Integration via HTTP | 55β65% | Validation, auth, EF queries, serialisation, ProblemDetails |
| Contract | A few per consumer | Messages and APIs other teams rely on |
| E2E smoke | 5β10 | Deployed health, login, one happy path |
On [an orders API], the suite was [about 900] unit tests with mocked repositories and 12 integration tests, yet [three of the last five] incidents were SQL or serialisation bugs. Moving to [about 250] WebApplicationFactory plus Testcontainers tests and deleting low-value mock tests kept CI at [roughly 6 minutes] and the next [two quarters] had no data-access regressions.
Checks whether the candidate can choose a test mix from risk and cost instead of reciting the pyramid.
Green flags
Red flags
The cost of a test has three parts: time to run, time to write and maintain, and time to diagnose when it fails. All three grow as the test includes more of the system:
/\ E2E: slow, broad, flaky, vague failures
/ \
/----\ Integration: real DB/HTTP, moderate speed
/ \
/--------\ Unit: fast, narrow, precise failures
The pyramid assumes unit tests catch most bugs. In modern web apps a lot of logic lives in frameworks and configuration: routing, model binding, validation attributes, EF Core mappings, JSON options, authorisation policies. A unit test bypasses all of that.
___
| E | few end-to-end
| I | integration = the biggest layer
| U | unit for real logic
|_S_| static: nullable, analysers, TreatWarningsAsErrors
The static layer matters in .NET: nullable reference types and Roslyn analysers catch a whole class of bugs before any test runs.
WebApplicationFactory<TEntryPoint> hosts the full pipeline in memory with TestServer: no ports, no network.The container start (several seconds for SQL Server) is paid once, then each test costs a few HTTP calls and queries.
For a service whose job is mostly integration (consume a message, call an API, write a row), Spotify argued for integrated tests around the service, with few implementation-detail tests and few integration tests across services (those are replaced by contract tests).
| Symptom | Likely cause |
|---|---|
| High coverage, bugs in SQL or JSON | Too many mock-based unit tests |
| CI takes 40 minutes | Too many E2E tests, or no container reuse |
| Refactors turn hundreds of tests red | Unit tests coupled to implementation |
| Nobody trusts red builds | Flaky E2E layer |
WebApplicationFactory and Testcontainers; measure per-test time after the first.The same rule tested at two layers: a unit test for the pricing logic, and an integration test for the endpoint that uses it.
#nullable enable
namespace Orders.Tests;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
// Unit layer: pure rule, microseconds, precise failure
public static class Discount
{
public static decimal Apply(decimal subtotal) => subtotal >= 200m ? subtotal * 0.9m : subtotal;
}
public sealed class DiscountTests
{
[Theory]
[InlineData(199.99, 199.99)]
[InlineData(200, 180)]
public void Apply_DiscountsOrdersFrom200(decimal subtotal, decimal expected)
=> Assert.Equal(expected, Discount.Apply(subtotal));
}
// Integration layer: routing, validation, serialisation, EF Core and SQL together.
// Program is the API's entry point; the factory is shared per class.
public sealed class CreateOrderEndpointTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Post_InvalidQuantity_Returns400ProblemDetails()
{
var response = await _client.PostAsJsonAsync(
"/orders", new { sku = "SKU-1", quantity = 0 }, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
}
}
TestContext.Current.CancellationToken is the xUnit v3 per-test token; in a real suite the factory would also swap the connection string to a Testcontainers database.
DbContext or repositories to keep tests "unit". Why it is wrong: LINQ translation, constraints and migrations go untested. Instead: Integration tests against a real database engine.[ApiController] automatic 400s, validation attributes and filters don't run when you call the method, so invalid input looks accepted. Instead: Test request validation through HTTP with WebApplicationFactory; unit-test validators (e.g. FluentValidation) on their own.TreatWarningsAsErrors in CI.The useful senior line is "the shape follows the risk, and the cost curve changed". Containers and in-memory hosting moved integration tests down the cost curve, so the trophy is often the cheaper way to get real confidence in .NET APIs. I still want a fast unit layer for genuine logic because it gives sub-second feedback while coding.
Infrastructure shapes the cost too. Microsoft-hosted Azure Pipelines and GitHub-hosted Linux runners have Docker available, so Testcontainers works without extra setup, but every container start is billed build minutes; a SQL Server image pull plus start can add 30β60 seconds per job, so I cache the image or use one container per run. For microservices, I don't spin up the whole system in CI: each service gets integrated tests with its own dependencies in containers, and contract tests (Pact or schema checks on Service Bus messages) cover the boundaries. Full end-to-end runs happen against a deployed test environment in Australia East after deployment, as a small smoke set.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Pyramid (unit-heavy) | Rule engines, libraries, algorithms | Cheap to run; misses wiring bugs | Thin CRUD APIs |
| Trophy (integration-heavy) | ASP.NET Core APIs with EF Core | Docker in CI, slower suite | When no container runtime is available |
| Honeycomb | Microservices with messaging | Needs contract tests too | Monoliths with rich domain logic |
I measure the balance with three numbers: CI suite time (target under ~10 minutes per PR), flaky-test rate, and the layer that would have caught each escaped defect.
Use WebApplicationFactory<Program> to start the real app in memory and send real HTTP requests through the whole pipeline: middleware, routing, model binding, validation, DI, authorisation and JSON. Run the things you own for real, including EF Core against a real SQL Server in Testcontainers, because that is where mapping, translation and migration bugs live. Fake the things you don't own: third-party HTTP APIs (WireMock.Net), email and SMS, the clock (FakeTimeProvider), and usually the identity provider via a test authentication handler. Keep tests isolated by resetting data between tests with Respawn and sharing one container per test collection. The trade-off is a few seconds of start-up for far more confidence than mocks give.
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.
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.
Last updated 23 Nov 2026.