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
