Good ways to test ASP.NET Web API applications using a simulated web server

Posted: (EET/GMT+2)

 

When you unit test ASP.NET Web API controllers, it's often best to run them inside a simulated host rather than mocking everything by hand. That way, you can test routing, filters, and model binding too, not just the controller logic.

In classic Web API, you can use the HttpServer class to spin up an in-memory host:

var config = new HttpConfiguration();
WebApiConfig.Register(config);

using (var server = new HttpServer(config))
using (var client = new HttpClient(server))
{
    var response = await client.GetAsync("http://localhost/api/values");
    string content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

For ASP.NET Core Web API, you can use TestServer class from the Microsoft.AspNetCore.TestHost namespace:

using Microsoft.AspNetCore.TestHost;
...
var builder = new WebHostBuilder()
    .UseStartup<Startup>();
var server = new TestServer(builder);
var client = server.CreateClient();

var response = await client.GetAsync("/api/values");
var text = await response.Content.ReadAsStringAsync();
Console.WriteLine(text);

This gives you a full pipeline test, including your controllers, middleware, and routing. They all run exactly as in production, but entirely in memory.

Happy testing!