Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 52 ยท Testing, Performance and Deployment

Testing ASP.NET Core Apps

Test ASP.NET Core apps with confidence: unit-test handlers and middleware, build an in-process integration test factory, swap in fakes and pin the clock.

A web application is easy to break and hard to check by hand. Every change might alter a route, a status code, a JSON shape or the order of middleware, and clicking through the application after each edit does not scale. Automated tests do. ASP.NET Core was designed to be testable: handlers are plain methods, services come from dependency injection, and the whole application can run inside the test process.

In this lesson you will learn the three levels of web tests (unit, component and integration), how to design code so it is easy to test, and how to build an in-process test application with replaceable dependencies. The runner on this site has no test framework, so the live examples use a ten-line harness that behaves like one. The real xUnit and WebApplicationFactory versions are shown read-only at the end, and the ideas carry over unchanged.

The test pyramid for web apps

flowchart TD
    A["Integration tests<br/>real pipeline, real HTTP, fake externals<br/>(few, slow, broad)"]
    B["Component tests<br/>middleware and filters with DefaultHttpContext<br/>(some)"]
    C["Unit tests<br/>handlers and services called directly<br/>(many, fast, narrow)"]
    A --- B --- C

Many small fast tests at the bottom, a few broad ones at the top.

  • Unit tests call a handler method or service directly with fake dependencies. They are fast and pinpoint failures, but they cannot notice a wrong route or a missing app.UseAuthentication().
  • Component tests run one piece of the pipeline (a middleware, a filter) against a hand-built HttpContext.
  • Integration tests start the real application (routing, binding, serialization, middleware, DI) and talk to it over HTTP. They catch wiring mistakes, which are the most common web bugs, but are slower.

Design for testability

Tests are easy when the code is built from small pieces with explicit dependencies. Four habits do most of the work:

  1. Handlers as methods, not big lambdas. static Task<...> Create(CreateOrder input, IOrderRepository repo, TimeProvider time) can be called from a test like any method, because minimal API binds its parameters from the container and the request, and a test simply passes them in.
  2. Depend on interfaces for things that touch the outside world: databases, other services, the file system, e-mail. A test passes a fake.
  3. Inject the clock. DateTime.UtcNow makes tests flaky. .NET's TimeProvider abstraction lets a test substitute a fixed time (Dependency Injection in ASP.NET Core shows how services reach handlers).
  4. Return TypedResults. A method that returns Results<Created<Order>, ValidationProblem> can be checked by type and by value, without any HTTP involved (Responses, Results and Content Negotiation).

A tiny harness

You do not need a framework to understand testing. A test is a named piece of code that throws if something is wrong. The harness below runs each test, catches exceptions and prints PASS or FAIL. It reproduces what xUnit's [Fact] and Assert.Equal do. We use it in every live example.

Unit-testing handlers

Here is a small orders feature with a repository interface, a handler and a fake clock. The tests call the handlers directly and then examine the typed result.

C# Unit tests for minimal API handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last test fails on purpose, so you can see what a failure report looks like: the test name, then an explanation of what was expected. Remove it and the run is green. Notice what the passing tests prove without any server running: the handler stores the order, stamps it with the injected time, and rejects bad input without touching the repository.

Name tests after behavior ("a quantity of zero is rejected"), not methods ("TestCreate2"). When one fails, the name alone should tell you what broke. Follow arrange, act, assert: set things up, perform one action, check the outcome.

Testing middleware with DefaultHttpContext

Middleware is a class that gets a RequestDelegate next. To test it you do not need a server: create a DefaultHttpContext, give it a MemoryStream as the response body, call the middleware and inspect what happened. A fake next records whether it was called.

C# Testing middleware without a server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

DefaultHttpContext is an ordinary class, so it is a quick way to test anything that takes an HttpContext: middleware, endpoint filters and helper methods. What it cannot show you is whether the middleware is actually registered in the right order in the real app. That is what the next level is for.

Integration tests: the whole app, in process

An integration test starts the real application inside the test process, sends real HTTP requests and checks real responses. In real projects you use WebApplicationFactory<Program> from the package Microsoft.AspNetCore.Mvc.Testing, which builds your actual Program.cs, uses an in-memory server instead of a network port and lets each test replace services (a fake repository, a fixed clock, a stub for an external API) before the app starts.

You can build the same idea in a few lines with plain Kestrel: a factory function that creates the app, applies the test's overrides after the normal registrations so they win, and starts on port 0, which makes the operating system pick a free port. Every test then gets its own isolated app and nothing collides.

flowchart LR
    A["Test"] --> B["Factory:<br/>build real app"]
    B --> C["Override services<br/>(fake repo, fixed clock)"]
    C --> D["Start on a free port"]
    A -->|"HttpClient"| D
    D --> E["Real routing, binding,<br/>JSON, middleware"]

The test drives the real pipeline over HTTP, while only the outside world is faked.

C# An in-process test factory with fakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three details deserve attention:

  • AppFactory.Create is the single place that builds the app. In a real project this is your Program.cs, which is why WebApplicationFactory needs Program to be accessible (add public partial class Program { } at the end of the file when using top-level statements).
  • Overrides are registered last. When several registrations exist for one service type, the container resolves the last one, so AddSingleton<IOrderRepository, BrokenOrders>() after the defaults replaces the repository. That is how you simulate a database outage and check that the app answers 500 instead of crashing.
  • A fresh app per test means tests never share state and can run in parallel. If startup is expensive, share one app per test class and reset its data between tests.

An integration test should still avoid the real outside world: real payment providers, real e-mail and the open internet make tests slow, flaky and sometimes expensive. Fake those boundaries with interfaces. For the database, use the same database engine as production when you can (for example in a container), because in-memory substitutes behave differently around transactions and SQL.

The same tests with xUnit and WebApplicationFactory

In a normal test project the pieces above are provided by packages. This code is read-only, because the site cannot reference test packages:

C#
// OrdersTests.cs  (project references Microsoft.AspNetCore.Mvc.Testing and xunit)
public class OrdersTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> factory;

    public OrdersTests(WebApplicationFactory<Program> factory) => this.factory = factory;

    [Fact]
    public async Task Post_creates_an_order()
    {
        HttpClient client = factory
            .WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
            {
                services.AddSingleton<IOrderRepository, InMemoryOrders>();
                services.AddSingleton<TimeProvider>(new FakeTimeProvider());
            }))
            .CreateClient();

        HttpResponseMessage response = await client.PostAsJsonAsync("/orders", new CreateOrder("Monitor", 1));

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-5)]
    public async Task Rejects_non_positive_quantities(int quantity) { /* ... */ }
}

The mapping is direct: [Fact] is one of our Run calls, Assert.Equal is Harness.Equal, ConfigureTestServices is the overrides parameter, and CreateClient() returns an HttpClient wired to an in-memory server (no port needed). FakeTimeProvider comes from the package Microsoft.Extensions.TimeProvider.Testing. Run everything with dotnet test.

What to test, and what not to

  • Test behavior that matters to callers: status codes, response shapes, validation, authorization rules, error handling.
  • Test edge cases and failures, not only the happy path: empty input, missing records, duplicate submissions, a dependency that throws.
  • Do not test the framework. There is no need to check that routing works for /orders/{id:int}; check that your route reaches your handler.
  • Keep tests independent and deterministic. No dependence on test order, the current time, random numbers (inject a seed) or the network.
  • Run tests in CI on every push, and treat a red build as the team's top priority.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does returning TypedResults from a handler make unit testing easier?

    A Results<Created<Order>, ValidationProblem> holds a concrete typed object, so a test can assert on its type, location and value directly.
  2. 2. What is the main thing an integration test catches that a handler unit test cannot?

    Unit tests call methods directly, bypassing routing, binding, serialization and middleware. An integration test sends real requests through the real pipeline.
  3. 3. How does a test replace a registered service with a fake in a WebApplicationFactory-style setup?

    The container resolves the last registration for a service type, so overrides added after the production registrations take effect (ConfigureTestServices does exactly this).
  4. 4. Why start a test server on port 0?

    Binding to port 0 makes the OS assign any free port. The test reads the actual address from the running app, and tests cannot clash over ports.
  5. 5. Which is the best way to make code that reads DateTime.UtcNow testable?

    TimeProvider is an abstraction for the clock. Production uses TimeProvider.System, tests pass a fixed or controllable implementation.

Summary

  • Web tests come in layers: many fast unit tests, some component tests with DefaultHttpContext, a few broad integration tests.
  • Make code testable with handler methods, interfaces for outside dependencies, an injected TimeProvider and TypedResults return types.
  • A test is code that throws when behavior is wrong; xUnit's [Fact] and Assert are conveniences around that idea.
  • Middleware and filters can be tested against a hand-built DefaultHttpContext with a fake next.
  • Integration tests run the real app in process, override services after the defaults and use a fresh app and a free port per test.
  • In real projects use xUnit, WebApplicationFactory<Program> and dotnet test; fake the outside world, not the pipeline.

Next: Performance Tuning