Lesson 61 of 93 · 5 min read · Updated
Unit Testing ASP.NET Core Minimal API Handlers with TypedResults
On this page
Minimal APIs make it easy to write an endpoint as a lambda inside MapGet. That is also what makes them hard to unit test: a lambda has no name, so a test cannot call it. This lesson moves the handler into a named static method, returns TypedResults, and tests the handler logic directly. It also draws the line between what a unit test covers and what needs an integration test.
Technical Requirements
- .NET 11 SDK
- An ASP.NET Core project using Minimal APIs
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- A test project with a
FrameworkReferencetoMicrosoft.AspNetCore.App(for theMicrosoft.AspNetCore.Http.HttpResultstypes)
Extract the Handler into a Named Method
Here is the stock endpoint. MapStockEndpoints only wires the route. The work happens in GetStockAsync, a public static method with plain parameters.
M07.WebApp/Endpoints/StockEndpoints.cs
Program.cs calls app.MapStockEndpoints();. At runtime, ASP.NET Core binds id from the route, repository from dependency injection and cancellationToken from the request. In a test, you pass those three arguments yourself. No HttpContext, no test server.
Compare that with the lambda version, app.MapGet("/api/stock/{id:int}", async (int id, IProductRepository repository, CancellationToken ct) => { ... }). The logic is the same, but it is buried inside the route registration. The only way to reach it is to start the whole application and send an HTTP request. Writing an inline lambda is a design choice, and the cost of that choice is that you cannot unit test the handler.
Why TypedResults
Results.Ok(...) returns IResult. A test would have to cast it and guess the type. TypedResults.Ok(...) returns Ok<StockResponse>, and the method's return type Results<Ok<StockResponse>, NotFound> lists every possible outcome. The compiler checks that the handler returns only those types, and the test can assert on them with no guessing.
Results<T1, T2> is a wrapper, much like ActionResult<T> in controllers. The actual result is in its Result property. That is why every assertion below starts with result.Result.
Testing the Handler
M07.WebApp.Tests/MinimalApiHandlerTests.cs
The tests read like calls to any other static method. Arrange a mock repository, call the handler, and check the typed result. Ok<StockResponse>.Value gives the response object directly, so the test checks the body fields without any JSON.
The success test sets up GetAsync for id 1 exactly, not with It.IsAny<int>(). That proves the handler passes the route id through to the repository. If the handler looked up the wrong id, the mock would return null, the handler would answer NotFound, and the test would fail. The handler also forwards the cancellation token, so an aborted request can stop the repository call.
Test the Threshold at the Boundary
The "low stock" flag uses <, not <=. That one character is the kind of detail that breaks silently. A [Theory] puts one case below the threshold, one exactly on it and one above it.
M07.WebApp.Tests/MinimalApiHandlerTests.cs
If someone changes the comparison to <=, the case with stock 5 fails and points to the exact boundary.
What This Test Does Not Cover
Calling the handler directly skips the whole request pipeline. The unit tests above do not check:
- Routing: that
/api/stock/7reaches this handler, or that the{id:int}constraint rejects/api/stock/abc. - Model binding: that
idcomes from the route andrepositoryfrom dependency injection. - Filters: endpoint filters added with
AddEndpointFilter. - Middleware: authentication, exception handling, and anything else in the pipeline.
- Serialization: the JSON shape the client really receives.
Those need an integration test that hosts the app in memory with WebApplicationFactory<Program> and sends real HTTP requests. The sample app already prepares for that with public partial class Program; at the end of Program.cs.
So pick the level by the question you ask. "Does the handler compute the right answer?" is a unit test. "Does a request to this URL reach the handler and return the right JSON?" is an integration test. Both are useful, and neither replaces the other.
Summary
- Write Minimal API handlers as named static methods, not inline lambdas, so tests can call them directly.
- Return
TypedResultsand declareResults<T1, T2>so the outcomes are explicit and easy to assert. - The real result sits in
result.Result; assert it withBeOfType<Ok<T>>()orBeOfType<NotFound>(). - Test numeric thresholds below, at and above the boundary.
- Routing, model binding, filters, middleware and serialization need integration tests.