skip to content

How do you unit test an ASP.NET Core 10 middleware or filter in a grocery app with DefaultHttpContext, and what does that context leave out?

level: seniorimportance: should knowfreq 42%

answer

  1. no server, no pipeline
  2. next as a RequestDelegate lambda
  3. Response.Body is Stream.Null
  4. RequestServices is null until assigned
  5. OnStarting callbacks never run

basics

~20 s

Build a DefaultHttpContext with the path, headers and services the code reads, pass a lambda as the next RequestDelegate, call InvokeAsync, then assert on status, headers, Items and whether next ran. Replace Response.Body with a MemoryStream to read output.

solid answer

~40 s

`DefaultHttpContext` is the framework's ordinary `HttpContext` implementation, so `new DefaultHttpContext()` gives you request and response objects without a server. Set `Request.Path`, `Request.Headers[...]` or `Request.Body`, then construct the middleware with `next: ctx => { nextCalled = true; return Task.CompletedTask; }` and call `InvokeAsync(context)`. Know what it lacks: `Response.Body` and `Request.Body` are `Stream.Null`, so writes vanish until you assign a `MemoryStream`; `RequestServices` is `null` until you assign a provider built from a `ServiceCollection`; `Response.HasStarted` is always `false` and `OnStarting`/`OnCompleted` callbacks are silently dropped; there is no endpoint unless you call `SetEndpoint`; `User` is an anonymous principal. Filters follow the same idea: an endpoint filter gets a `DefaultEndpointFilterInvocationContext(httpContext, args)` and a delegate as `next`, and an MVC action filter gets an `ActionExecutingContext` built over `new ActionContext(httpContext, new RouteData(), new ActionDescriptor())`.

code

csharp · 20 lines
csharp
[Fact]
public async Task Missing_store_header_returns_400_and_stops()
{
    var nextCalled = false;
    var middleware = new StoreSelectionMiddleware(_ =>
    {
        nextCalled = true;
        return Task.CompletedTask;
    });
    var context = new DefaultHttpContext();
    context.Response.Body = new MemoryStream(); // default is Stream.Null

    await middleware.InvokeAsync(context);

    Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
    Assert.False(nextCalled);
    context.Response.Body.Position = 0;
    var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
    Assert.Contains("X-Store-Id", body);
}

go deeper

for a junior

Know that DefaultHttpContext lets you call middleware directly and that next is just a delegate you write in the test.

for a middle

List the defaults that trip tests: Stream.Null bodies, null RequestServices, dropped OnStarting callbacks, no endpoint and an anonymous user.

for a senior

Decide which middleware and filter rules a DefaultHttpContext test can prove and which need a booted pipeline, and build the filter contexts correctly.

for a principal

Set guidance on when teams unit test middleware directly versus through the host, so fast tests do not give false confidence about ordering.

## What DefaultHttpContext is `DefaultHttpContext` is the concrete `HttpContext` that ASP.NET Core itself uses, assembled from **features** (`IHttpRequestFeature`, `IHttpResponseFeature`, `IHttpResponseBodyFeature` and others). A server normally supplies those features. Constructed with `new DefaultHttpContext()`, it installs simple in-memory defaults instead, which makes it ideal for calling a middleware or filter directly, and misleading where the defaults differ from a real server. ## The grocery middleware under test `StoreSelectionMiddleware` reads an `X-Store-Id` header. Without it the middleware answers 400 and stops; with it, it stores the id in `HttpContext.Items` and calls `next`. Three facts need checking: the status on the short-circuit path, that `next` was not called there, and that `Items["StoreId"]` is set on the happy path. 1. Arrange a `DefaultHttpContext` and set `Request.Headers["X-Store-Id"] = "17"` (or leave it out). 2. Create the middleware with a lambda `RequestDelegate` that records whether it ran. 3. Call `await middleware.InvokeAsync(context)`. 4. Assert on `context.Response.StatusCode`, `context.Items` and the flag. ## What the defaults are, and what they leave out | Area | `new DefaultHttpContext()` gives | What to do in the test | |---|---|---| | response status | `200` | assert changes explicitly | | response body | `Stream.Null`, writes discarded | assign `new MemoryStream()` before invoking, rewind to read | | request body | `Stream.Null` | assign a `MemoryStream` holding the payload | | `RequestServices` | `null` | build a `ServiceCollection`, then `BuildServiceProvider()` | | `Response.HasStarted` | always `false` | test header rules with an integration test instead | | `OnStarting` / `OnCompleted` | callbacks dropped, never run | same | | endpoint and route | none | call `SetEndpoint(...)` if the code reads metadata | | `User` | an unauthenticated `ClaimsPrincipal` | assign a principal with an authentication type | The `RequestServices` row catches people executing an `IResult` in a unit test: many results resolve `ILoggerFactory` or JSON options from `RequestServices`, so a provider built with `AddLogging()` must be assigned first. ## Testing filters The same context drives filter tests: - **Endpoint filters** (`IEndpointFilter`) take an `EndpointFilterInvocationContext` and an `EndpointFilterDelegate`. Build `new DefaultEndpointFilterInvocationContext(httpContext, coupon, basket)` with the handler's arguments in order, and pass `next` as a lambda returning a `ValueTask<object?>`. Assert on the returned object or on whether `next` ran. - **MVC action filters** need an `ActionExecutingContext`. Build an `ActionContext(httpContext, new RouteData(), new ActionDescriptor())`, then `new ActionExecutingContext(actionContext, new List<IFilterMetadata>(), actionArguments, controller)`. A filter that short-circuits sets `context.Result`; assert on it. ## Where a DefaultHttpContext test stops being honest - Code that sets headers in `OnStarting`, relies on `HasStarted`, or streams the response behaves differently under a real server; those rules need a `WebApplicationFactory` test. - Middleware whose correctness depends on **position** (after routing, before authorization) cannot be checked in isolation, because the context has no pipeline. - Features such as `IHttpConnectionFeature` hold empty defaults, so `Connection.RemoteIpAddress` is `null` unless you set it. ## Request bodies and endpoint metadata Two more setups come up often: - **A request body.** Serialise the payload into a `MemoryStream`, assign it to `Request.Body`, and set `Request.ContentType` and `Request.ContentLength` if the code checks them. Middleware that reads the body twice also needs buffering, which a plain `MemoryStream` already allows because it is seekable. - **Endpoint metadata.** Middleware that reacts to attributes reads `context.GetEndpoint()?.Metadata`. Give it one with `context.SetEndpoint(new Endpoint(null, new EndpointMetadataCollection(new RequiresStoreAttribute()), "test"))`, where the attribute is the app's own marker. ## Practical tips - Build contexts through a small helper so each test sets only what it cares about. - Rewind with `body.Position = 0` before reading a `MemoryStream`, or the read returns an empty string. - Keep doubles for the middleware's own constructor dependencies, and a real `ServiceCollection` for what it resolves per request.

  • A middleware adds a response header inside Response.OnStarting. Its DefaultHttpContext test never sees the header. Why?
    The default response feature's `OnStarting` ignores the callback, and `HasStarted` never becomes true, because no server starts the response. Test that behaviour through `WebApplicationFactory`, or refactor the header logic into a method you can call directly.
  • The middleware resolves a scoped service from context.RequestServices. What must the test provide?
    Assign `context.RequestServices` from a `ServiceCollection` with the needed registrations, usually inside a scope created from the built provider. Without it, `RequestServices` is null and the resolution throws a `NullReferenceException` or `ArgumentNullException`.

  • Writes to a new DefaultHttpContext's response can be read back without setting Body.
  • DefaultHttpContext runs OnStarting callbacks when the middleware returns.
  • RequestServices on a new DefaultHttpContext resolves the app's registered services.
  • A DefaultHttpContext test proves the middleware is in the right pipeline position.
  • DefaultHttpContext is a test-only mock type shipped by Mvc.Testing.