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
