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

πŸ“š Interview question

What is the test pyramid, and how does it differ from the testing trophy and the honeycomb? How would you balance unit and integration tests for a typical ASP.NET Core API backed by SQL Server?

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.

Intermediate Theory Intermediate aspnet-core integration-testing test-pyramid testing testing-trophy unit-testing

🎯 Key points

  • Pyramid (Mike Cohn): many fast unit tests, fewer integration tests, very few end-to-end tests
  • Trophy (Kent C. Dodds): static analysis base, integration tests as the largest layer
  • Honeycomb (Spotify): for microservices, mostly integrated tests per service, with contract tests replacing cross-service integration tests
  • The shape follows where the risk is: logic-heavy code favours unit tests, I/O-heavy code favours integration tests
  • WebApplicationFactory plus Testcontainers makes API integration tests cheap enough to be the bulk
  • End-to-end tests stay few: slow, flaky and expensive to debug
  • Keep integration tests fast in CI: shared containers, parallel collections, split jobs
  • Measure with suite time, flake rate and escaped defects, not test counts

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 DbContext proves almost nothing, and the real bugs are a wrong Include, a missing migration, a JSON casing change or a broken authorisation policy. Those only show up when the pieces run together. With WebApplicationFactory hosting 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."


The three models

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

Cost per layer (typical .NET numbers)

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

A balanced mix for an orders API

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

Production example

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.

πŸ” What the interviewer is checking

Checks whether the candidate can choose a test mix from risk and cost instead of reciting the pyramid.

Green flags

  • Knows pyramid, trophy and honeycomb and why each exists
  • Ties the choice to where bugs occur in the system
  • Mentions WebApplicationFactory and Testcontainers as what makes integration tests cheap
  • Measures with escaped defects and CI time

Red flags

  • Fixed ratios as a rule ("70/20/10 always")
  • Mocking DbContext to keep everything unit
  • Relies on E2E as the main safety net

πŸ“š Learn in depth

1. Why the pyramid shape exists

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

2. Why the trophy appeared

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.

3. What made integration tests cheap in .NET

  • WebApplicationFactory<TEntryPoint> hosts the full pipeline in memory with TestServer: no ports, no network.
  • Testcontainers starts a real SQL Server or Redis in Docker; one container per test run or per collection fixture.
  • Respawn or transaction rollback resets data in milliseconds between tests.

The container start (several seconds for SQL Server) is paid once, then each test costs a few HTTP calls and queries.

4. The honeycomb for microservices

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).

5. How to tell your shape is wrong

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

Try it yourself

  1. Classify the last ten production bugs in your service by which layer would have caught them cheapest.
  2. Write one endpoint test with WebApplicationFactory and Testcontainers; measure per-test time after the first.
  3. Delete (on a branch) unit tests that only verify repository calls and see whether mutation score drops.
  4. Turn on nullable warnings as errors in one project and count the issues found before tests run.

πŸ’» Code

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.

⚠ Common mistakes

  • Mistake: Treating the pyramid as a law with fixed ratios. Why it is wrong: It was a cost heuristic; the right mix depends on where bugs actually occur. Instead: Shape the suite around your defect history.
  • Mistake: Mocking 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.
  • Mistake: Unit-testing controllers by calling action methods directly and assuming validation ran. Why it is wrong: Model binding, [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.
  • Mistake: Making end-to-end browser tests the main safety net. Why it is wrong: Slow, flaky, and failures are hard to locate. Instead: A small smoke set; push checks down to integration.
  • Mistake: Growing the integration layer without managing CI time. Why it is wrong: A 40-minute pipeline makes people batch changes and skip local runs. Instead: Start containers once per run, reset data with Respawn, run collections in parallel, and split long suites across CI jobs.
  • Mistake: Counting tests per layer as the success metric. Why it is wrong: Numbers say nothing about what is caught. Instead: Track escaped defects, flake rate and CI time.
  • Mistake: Ignoring the static layer. Why it is wrong: Null bugs and API misuse can be caught for free at compile time. Instead: Nullable on, analysers, TreatWarningsAsErrors in CI.
  • Mistake: Testing cross-service flows with integration tests against real other services. Why it is wrong: Shared environments make them slow and flaky. Instead: Contract tests at service boundaries.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says integration tests should be the biggest layer Why: Checks what they run for real and what they fake in API integration tests
    How to answer

    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.

  2. When: Candidate gives percentages for each layer Why: Checks they can turn the shape into a concrete strategy with merge and release gates
    How to 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.

  3. When: Candidate is vague about where unit tests end Why: Checks the definitions of unit, integration and end-to-end
    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.

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me