liveBook · Manning

GetTestClient

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

GetTestClient is a TestServer extension method that creates an HttpClient configured to send requests to the server in memory.

GetTestClient creates an HttpClient configured to send requests to a TestServer in memory. Start the test host first, then use the client as though it were sending a network request. section 36.3.1

Send an in-memory request

Configure a HostBuilder with UseTestServer(), start it asynchronously, and obtain the client with host.GetTestClient(). A call such as client.GetAsync("/ping") passes through the middleware pipeline; the test can then verify the response status and content. 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
    }
}

The complete TestServer example shows the required order: configure the application, enable TestServer, start the host, create the client, and issue a request. section 36.3.1

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

How deep it goes
Explains client creation and request behavior, but defers full application hosting and real-application integration configuration.
Examples
Demonstrates a /ping request against StatusMiddleware configured in a TestServer.
What it assumes
Assumes familiarity with HostBuilder, middleware configuration, asynchronous host startup, and the Test Host package.
What you can do after
Apply GetTestClient to issue and verify in-memory HTTP requests against a configured TestServer.
How it connects
Connects HostBuilder, TestServer, HttpClient, middleware, 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.