liveBook · Manning

UseTestServer

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

UseTestServer is an ASP.NET Core hosting extension method that configures an application to use TestServer instead of a network web server.

UseTestServer configures an ASP.NET Core application to run with TestServer instead of Kestrel. The application receives requests through an HttpClient, but middleware processes them as ordinary HTTP requests. section 36.3.1

A minimal test-host setup follows these steps:

  • Create a HostBuilder and configure the web host. section 36.3.1
  • Register middleware and call UseTestServer(). section 36.3.1
  • Start the host asynchronously, obtain a test client with GetTestClient(), and send in-memory requests. section 36.3.1
Listing 36.7 Creating an integration test with TestServer
public class StatusMiddlewareTests
{
    [Fact]
    public async Task StatusMiddlewareReturnsPong()
    {
        var hostBuilder = new HostBuilder()                        #1
            .ConfigureWebHost(webHost =>                           #1
            {
                webHost.Configure(app =>                           #2
                    app.UseMiddleware<StatusMiddleware>());        #2
                webHost.UseTestServer();                           #3
            });
 
        IHost host = await hostBuilder.StartAsync();               #4
        HttpClient client = host.GetTestClient();                  #5
 
        var response = await client.GetAsync("/ping");             #6
 
        response.EnsureSuccessStatusCode();                        #7
        var content = await response.Content.ReadAsStringAsync();  #8
        Assert.Equal("pong", content);                             #8
    }
}

Shows a complete middleware test that configures TestServer, requests /ping, checks the response status, and reads its content. section 36.3.1

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

How deep it goes
Explains registration, host startup, client creation, and request execution, while deferring broader application configuration.
Examples
Uses a StatusMiddleware test that sends an in-memory GET request to /ping and verifies the response.
What it assumes
Assumes familiarity with ASP.NET Core middleware and hosting, while demonstrating the test-host setup explicitly.
What you can do after
Build integration tests with HostBuilder, TestServer, and GetTestClient() for in-memory middleware requests.
How it connects
Connects TestServer with HostBuilder, ConfigureWebHost, Kestrel, middleware, HttpClient, and integration testing.

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.