I recently had do a project where I wanted to run integration tests on some Web API controllers, so this post is to describe the method for doing so.
The way to do it is to mock an HttpServer and HttpClient class, but first you have to change some of the config to get them working correctly.
In the WebApiConfig in App_Start, create two overloaded methods for mapping HTTP routes – one that takes a RouteCollection as a parameter(for when running in debug/production), and one that takes an HttpRouteCollection (for when running integration tests).
You will also have to define your own class for a Route – with Name, Template and Defaults properties.
Then call the AddHttpRoutes method during application startup (I placed it in the RegisterRoutes method of RouteConfig) to configure the routing on the Web API controllers.
So now we are ready to set up some integration tests – in my sample I am using NUnit.
In your test setup you will need to instantiate an HttpClient and pass a configured HttpServer as a parameter (using the overloaded AppHttpRoutes method to configure it).
Now you can create an HttpRequest and use the HttpClient to send the request and hit your Web API controllers, then run your assertions on the HttpResponse that is returned.
And that’s it. Now you can run integration tests against your Web API controllers – useful for checking if your routes are correctly configured.