Lesson 61 of 93 · 5 min read · Updated

Unit Testing ASP.NET Core Minimal API Handlers with TypedResults

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

  1. .NET 11 SDK
  2. An ASP.NET Core project using Minimal APIs
  3. xUnit 2.9.3
  4. Moq 4.21.0
  5. FluentAssertions 7.2.2
  6. A test project with a FrameworkReference to Microsoft.AspNetCore.App (for the Microsoft.AspNetCore.Http.HttpResults types)

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

/// <summary>Stock information response.</summary>
public sealed record StockResponse(int ProductId, int Available, bool IsLow);

/// <summary>
/// TIP: extract the handler into a NAMED method.
/// That way:
/// - you can UNIT test the handler logic (as below),
/// - you write INTEGRATION tests for routing / model binding / filters / middleware.
///
/// Using TypedResults makes the return type testable too.
/// </summary>
public static class StockEndpoints
{
/// <summary>Stock below this threshold counts as "low".</summary>
public const int LowStockThreshold = 5;

/// <summary>Maps the endpoints onto the application.</summary>
public static void MapStockEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/api/stock/{id:int}", GetStockAsync).WithName("GetStock");
}

/// <summary>
/// A PURE handler: it can be called directly and tested directly.
/// It does not need an HttpContext.
/// </summary>
public static async Task<Results<Ok<StockResponse>, NotFound>> GetStockAsync(
int id,
IProductRepository repository,
CancellationToken cancellationToken)
{
var product = await repository.GetAsync(id, cancellationToken);

if (product is null)
{
return TypedResults.NotFound();
}

return TypedResults.Ok(
new StockResponse(product.Id, product.Stock, product.Stock < LowStockThreshold));
}
}

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

[Fact]
public async Task GetStockAsync_WhenProductExists_ReturnsOkWithStock()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Product(1, "Klavye", 750m, stock: 12));

var result = await StockEndpoints.GetStockAsync(1, repository.Object, CancellationToken.None);

var ok = result.Result.Should().BeOfType<Ok<StockResponse>>().Subject;
ok.Value!.Available.Should().Be(12);
ok.Value.IsLow.Should().BeFalse();
}

[Fact]
public async Task GetStockAsync_WhenProductIsMissing_ReturnsNotFound()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Product?)null);

var result = await StockEndpoints.GetStockAsync(99, repository.Object, CancellationToken.None);

result.Result.Should().BeOfType<NotFound>();
}

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

[Theory]
[InlineData(4, true)] // below the threshold -> low
[InlineData(5, false)] // BOUNDARY: at the threshold -> NOT low
[InlineData(6, false)]
public async Task GetStockAsync_MarksLowStockAtThreshold(int stock, bool expectedIsLow)
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Product(1, "Klavye", 750m, stock));

var result = await StockEndpoints.GetStockAsync(1, repository.Object, CancellationToken.None);

result.Result.Should().BeOfType<Ok<StockResponse>>()
.Which.Value!.IsLow.Should().Be(expectedIsLow);
}

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:

  1. Routing: that /api/stock/7 reaches this handler, or that the {id:int} constraint rejects /api/stock/abc.
  2. Model binding: that id comes from the route and repository from dependency injection.
  3. Filters: endpoint filters added with AddEndpointFilter.
  4. Middleware: authentication, exception handling, and anything else in the pipeline.
  5. 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

  1. Write Minimal API handlers as named static methods, not inline lambdas, so tests can call them directly.
  2. Return TypedResults and declare Results<T1, T2> so the outcomes are explicit and easy to assert.
  3. The real result sits in result.Result; assert it with BeOfType<Ok<T>>() or BeOfType<NotFound>().
  4. Test numeric thresholds below, at and above the boundary.
  5. Routing, model binding, filters, middleware and serialization need integration tests.