How to test WebAPI with In-Memory Hosting

In most cases you want to have integration tests for your WebAPI, but don’t deploy it on IIS. There is an option which allows to skip IIS pipeline and work only with ASP.NET one. You may create an HTTP server in memory and call the same endpoints as usual. This is easy and allows to cover your API with required tests.

In order to do that you should create an instance of
HttpServer class. This class is available after the NuGet package is installed
Microsoft.AspNet.WebApi.Core. This code may be located in test setup method.

C#

1

2

3

4

5

6

privatereadonlyHttpServer _httpServer;

...

varconfig=newHttpConfiguration();

WebApiApplication.Configure(config);// config of your Web API

config.IncludeErrorDetailPolicy=IncludeErrorDetailPolicy.Always;

_httpServer=newHttpServer(config);

Now you can create a request to the server and call required URL. Below you can find two methods. The 1st creates a request without data, the 2nd one uses Content to pass data to the server.