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.

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.

The test of some endpoint with GET method could look as follows. It expects URL <host>/api/values returns some value.

When you need to get a response result, you should cast Content to specific type.

See also




No Comments


You can leave the first : )



Leave a Reply