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

📚 Interview question

What is the difference between unit, integration and end-to-end tests? Explain what each one proves, how fast and costly each is, and where you draw the lines in an ASP.NET Core API.

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.

Beginner Theory Beginner aspnet-core end-to-end-testing integration-testing testing unit-testing xunit

🎯 Key points

  • Unit test: one unit of behaviour through its public API, in memory, no I/O, milliseconds; private helpers are covered indirectly
  • Unit tests replace process boundaries with test doubles; integration tests use the real collaborators
  • Integration test: real SQL Server (an isolated Testcontainers instance), HTTP pipeline and serialisation, seconds, proves the parts fit
  • End-to-end test: the deployed system through its public surface (browser or HTTP), slowest and most brittle
  • In ASP.NET Core: WebApplicationFactory plus a real database is the usual integration boundary
  • Integration tests reset or clean up their data (Respawn, transactions) so they stay order-independent
  • Most tests unit or integration, a thin layer of E2E on critical journeys
  • A failing E2E test tells you something is broken, not where

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DbContext isn'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."


The three types side by side

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

Where the lines sit in an ASP.NET Core API

  • Unit: domain entities, value objects, validators (FluentValidation), pricing and eligibility rules, mapping functions, pure helpers. Anything with logic and no I/O.
  • Integration: each endpoint through 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.
  • End-to-end: a deployed test environment in Azure, the real front end via Playwright or the real API with real tokens from Microsoft Entra ID, run after deployment as a release gate.

What each one cannot catch

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate knows what each test type actually proves, rather than reciting the pyramid.

Green flags

  • Defines each type by what is real, not by tool.
  • Names WebApplicationFactory and a real database for integration tests.
  • Explains what each type cannot catch.
  • Mentions speed and failure precision trade-offs with rough numbers.

Red flags

  • Calls mock-heavy tests integration tests.
  • Thinks more E2E tests always means more safety.
  • Treats coverage percentage as the goal.

📚 Learn in depth

1. What "unit" means

A unit is a unit of behaviour, not necessarily one class. Two schools exist:

  • Classical (Detroit): test a behaviour through its public API, using real collaborators unless they are slow or shared (database, network, clock). Tests survive refactoring.
  • London (mockist): isolate each class and mock every collaborator. Tests pin down interactions and break when you refactor internals.

Most modern .NET teams lean classical: mock only what crosses a process boundary.

2. The confidence and cost curve

 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.

3. How an ASP.NET Core integration test works

 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.

4. End-to-end in practice

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.

5. Choosing the level for a new test

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.

Try it yourself

  1. Write a unit test for a discount rule and time it with dotnet test --logger "console;verbosity=detailed".
  2. Add Microsoft.AspNetCore.Mvc.Testing and write one WebApplicationFactory test hitting /health.
  3. Remove a DI registration and see which of your tests fail.
  4. Rename a DTO property and check whether any test notices; if not, add a JSON shape assertion.
  5. Compare the run time of 100 unit tests vs 10 integration tests.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Calling a test that mocks the 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.
  • Mistake: Writing E2E tests for every edge case. Why it is wrong: they are slow, flaky and expensive to maintain, and a failure doesn't say where. Instead: cover edge cases with unit tests and keep E2E to critical journeys.
  • Mistake: Only writing unit tests. Why it is wrong: DI registrations, routing, serialisation and SQL are never exercised until production. Instead: add at least one integration test per endpoint.
  • Mistake: Defining "unit" as "one class" and mocking every collaborator. Why it is wrong: tests lock in implementation details and break on every refactor. Instead: test behaviour through a public API and mock only process boundaries.
  • Mistake: Sharing one database between integration tests without resetting it. Why it is wrong: tests depend on order and become flaky. Instead: reset state between tests (Respawn, transactions) or give each test its own data.
  • Mistake: Running E2E tests on every pull request against a shared environment. Why it is wrong: parallel PRs collide and block each other. Instead: run them after deployment to a dedicated environment.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions running the different test types in the pipeline. Why: Checks the candidate can actually run, filter and report tests in CI.
    How to answer

    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.

  2. When: Candidate mentions using a real database in integration tests. Why: Checks how the candidate gets a real SQL Server into integration tests.
    How to answer

    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.

  3. When: Candidate mentions faking the database to make integration tests faster. Why: Checks the candidate knows the in-memory provider is not a relational database.
    How to answer

    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.

↩ Usually asked after

More in Test Types

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me