Unit, integration and end-to-end tests: what each proves, their speed, cost and failure signal, and where the boundaries sit in a .NET 10 ASP.NET Core API.
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.
"The three differ in how much real stuff they include. A unit test exercises one unit of behaviour, usually a class or a small cluster of classes, entirely in memory. No database, no network, no file system. It runs in milliseconds, so I can have thousands, and when one fails it points straight at the logic that's wrong.
An integration test includes real collaborators. In an ASP.NET Core API that usually means spinning the app up in memory with
WebApplicationFactory, sending real HTTP requests through routing, model binding, filters and serialisation, and letting EF Core talk to a real SQL Server in a container. It proves the pieces fit: the JSON shape, the migration, the SQL EF Core generates, the DI registrations. Each test takes tens or hundreds of milliseconds and the suite takes a minute or two. An end-to-end test runs against the deployed system, through a browser with Playwright or through the public API, including real identity, networking and configuration. It proves a user journey works, but it is slow, needs an environment, and when it fails it tells me something is broken, not where.The mistake I see is drawing the lines by tool rather than by what's real. A test that mocks the
DbContextisn't an integration test, it's a unit test with extra pain. I'd rather have a solid layer of fast unit tests for business rules, integration tests for every endpoint against a real database, and a handful of E2E tests on the journeys that make money. Each layer should catch a kind of bug the others can't."
| Unit | Integration | End-to-end | |
|---|---|---|---|
| Scope | One behaviour, in memory | Several real components | Whole deployed system |
| Real I/O | None | Database, HTTP pipeline, sometimes a broker | Everything, including identity and network |
| Typical speed | 1–10 ms | 50–500 ms | Seconds to minutes |
| Typical count | Hundreds to thousands | Tens to hundreds | A handful to a few dozen |
| Failure tells you | Exactly which rule broke | Which boundary or wiring broke | That a journey is broken |
| Main risk | Testing mocks, not behaviour | Slow or shared state | Flakiness and maintenance cost |
WebApplicationFactory<Program> with HttpClient; EF Core queries and migrations against SQL Server via Testcontainers; message handlers against a real or emulated broker; outbound HTTP against WireMock.Net.| Bug | Unit | Integration | E2E |
|---|---|---|---|
| Wrong discount calculation | Yes | Maybe | Rarely pinpoints |
| Missing DI registration | No | Yes | Yes |
| EF Core query that can't be translated | No | Yes | Yes |
| JSON property renamed, client breaks | No | Yes, if asserted | Yes |
| Wrong App Service setting or Key Vault permission | No | No | Yes |
A team had 1,800 unit tests at 95% line coverage, yet a release failed because a new handler was never registered in DI, giving 500s on one endpoint. Adding 60 WebApplicationFactory tests (one per endpoint, about 40 seconds in CI) caught the same class of bug in the next three releases before deployment.
Checks whether the candidate knows what each test type actually proves, rather than reciting the pyramid.
Green flags
WebApplicationFactory and a real database for integration tests.Red flags
A unit is a unit of behaviour, not necessarily one class. Two schools exist:
Most modern .NET teams lean classical: mock only what crosses a process boundary.
confidence that production works
^
E2E | *
|
Integ. | *
|
Unit | *
+--------------------------------> cost per test
ms 100s ms seconds-minutes
stable mostly stable flaky
precise boundary-level vague
Each step up includes more real components, so it catches more classes of bug, but costs more to run and to diagnose.
xUnit test
|
v
WebApplicationFactory<Program>
| builds the real host from Program.cs
| replaces config / services if you ask it to
v
TestServer (in memory, no sockets)
|
v
middleware -> routing -> model binding -> endpoint -> EF Core
|
v
SQL Server in a Testcontainers container
TestServer swaps Kestrel for an in-memory IServer, so requests skip the network but go through every piece of your pipeline. That is why it catches DI, routing, serialisation and authorisation mistakes.
E2E tests run against a deployed environment: real Azure App Service or Container Apps, real Key Vault, real identity. They catch configuration and infrastructure bugs. Keep them few, idempotent (create their own data), and run them as a post-deployment gate rather than on every commit.
Ask: what is the cheapest test that would fail if this bug existed? Logic bug → unit. Wiring, SQL or contract bug → integration. Config or infrastructure bug → E2E or smoke test.
dotnet test --logger "console;verbosity=detailed".Microsoft.AspNetCore.Mvc.Testing and write one WebApplicationFactory test hitting /health.A unit test and an integration test for the same feature, in xUnit on .NET 10:
// Production code
namespace Shop.Pricing;
public sealed record Order(decimal Subtotal, bool IsMember);
public static class DiscountCalculator
{
// Members get 10% off orders of $100 or more.
public static decimal Total(Order order) =>
order.IsMember && order.Subtotal >= 100m
? Math.Round(order.Subtotal * 0.9m, 2)
: order.Subtotal;
}
// Unit test: pure logic, no I/O, runs in milliseconds
namespace Shop.Tests.Unit;
using Shop.Pricing;
using Xunit;
public sealed class DiscountCalculatorTests
{
[Theory]
[InlineData(100, true, 90)]
[InlineData(99.99, true, 99.99)]
[InlineData(200, false, 200)]
public void Total_applies_member_discount_from_100(decimal subtotal, bool member, decimal expected)
{
var total = DiscountCalculator.Total(new Order(subtotal, member));
Assert.Equal(expected, total);
}
}
// Integration test: real pipeline in memory (routing, binding, DI, JSON)
namespace Shop.Tests.Integration;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class PricingEndpointTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
private sealed record QuoteResponse(decimal Total);
[Fact]
public async Task Post_quote_returns_discounted_total()
{
var client = factory.CreateClient();
var response = await client.PostAsJsonAsync("/quotes",
new { subtotal = 150m, isMember = true }, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadFromJsonAsync<QuoteResponse>(TestContext.Current.CancellationToken);
Assert.Equal(135m, body!.Total);
}
}
TestContext.Current.CancellationToken is the xUnit v3 test cancellation token; Program needs public partial class Program; if it uses top-level statements.
DbContext or repository an integration test. Why it is wrong: nothing real is integrated, so SQL translation, mappings and migrations are untested. Instead: use a real SQL Server (Testcontainers) for anything that claims to test data access.The useful question is not "how many unit tests" but "what is the cheapest test that would catch this bug?". Logic belongs in unit tests; anything involving a boundary (HTTP, SQL, serialisation, DI) belongs in integration tests; configuration and infrastructure belong in a small set of post-deployment E2E or smoke tests. ASP.NET Core makes integration tests cheap with WebApplicationFactory, and Testcontainers makes a real database cheap, so the old fear of slow integration tests is mostly outdated.
| Test type | When it fits | Cost | When not to |
|---|---|---|---|
| Unit | Business rules, calculations, validation | Very low | Code that is mostly wiring or SQL |
| Integration | Endpoints, EF Core queries, handlers | Low to medium | Pure logic already unit tested |
| E2E | Revenue-critical journeys, config | High | Edge cases and error permutations |
Measure the suite by escaped defects and run time, not by coverage alone.
dotnet test builds the test projects and runs them through the test platform, using the adapter the project references (xUnit, NUnit or MSTest). I use --filter to pick tests, for example --filter "Category=Unit&FullyQualifiedName~Orders". I use --logger trx so CI can show the results, and --collect "XPlat Code Coverage" with Coverlet for coverage, which I turn into a report. When tests hang or crash, --blame-hang-timeout and --blame-crash capture dumps. The command exits non-zero on failure, so the pipeline fails. In .NET 10 the SDK can also run in Microsoft.Testing.Platform mode, which you opt into in global.json.
Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.
Not for anything that tests data access. The EF Core in-memory provider runs LINQ against in-memory collections; it never generates SQL, so untranslatable queries, SQL Server collation and case-sensitivity, null semantics, constraints, foreign keys, unique indexes and transactions all behave differently, and tests pass that would fail on SQL Server. Microsoft's EF Core testing docs discourage it for testing. It can still serve quick tests of application logic that merely uses a DbContext, where speed matters more than fidelity. For integration tests use SQL Server in Testcontainers (or SQLite in-memory as a compromise with a different dialect), and reset state with Respawn or rolled-back transactions.
Last updated 23 Nov 2026.