liveBook · Manning

Microsoft.AspNetCore.TestHost

As explained in ASP.NET Core in Action, 3e

Microsoft.AspNetCore.TestHost is an ASP.NET Core library that provides infrastructure for hosting and testing applications in memory.

Microsoft.AspNetCore.TestHost provides an in-memory ASP.NET Core server for integration tests. It lets tests send HTTP requests and inspect responses without starting a separate process, opening a port, or coordinating server shutdown. section 35.1 section 36.3.1

A Test Host integration test typically:

  • Builds a HostBuilder and configures the middleware pipeline. section 36.3.1
  • Calls UseTestServer() instead of configuring a network-listening server. section 36.3.1
  • Starts the host and obtains an HttpClient with GetTestClient(). section 36.3.1
  • Sends requests and verifies status codes, response bodies, or other results. section 36.3.1

Testing middleware with TestServer

var host = await new HostBuilder().ConfigureWebHost(webHost => { webHost.Configure(app => app.UseMiddleware<StatusMiddleware>()); webHost.UseTestServer(); }).StartAsync(); var client = host.GetTestClient(); var response = await client.GetAsync("/ping"); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); The middleware runs inside ASP.NET Core infrastructure, while the request remains in memory.

<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.0"/>

Add Microsoft.AspNetCore.TestHost to the test project with this package reference. section 36.3.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Demonstrates package setup, HostBuilder configuration, TestServer startup, HttpClient requests, and response assertions; defers full-application testing to WebApplicationFactory.
Examples
Uses a StatusMiddleware /ping request to demonstrate successful in-memory responses and response-body inspection.
What it assumes
Assumes familiarity with ASP.NET Core hosting, middleware, HostBuilder, and basic test-project setup.
What you can do after
Operate/configure an in-memory ASP.NET Core host and verify middleware responses through an HttpClient.
How it connects
Connects integration testing with HostBuilder, middleware pipelines, HttpClient, TestServer, Kestrel, and WebApplicationFactory.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.