Skip to content
Mike Evans-Larah By Mike Evans-Larah Software Engineer III
Integration testing with Web API

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.

The Introduction to Rx.NET 2nd Edition (2024) Book, by Ian Griffiths & Lee Campbell, is now available to download for FREE.

And that's it. Now you can run integration tests against your Web API controllers - useful for checking if your routes are correctly configured.

Discover your Power BI Maturity Score by taking our FREE 5 minute quiz.

Check out the full sample on the endjin samples GitHub repo.


Mike Evans-Larah

Software Engineer III

Mike Evans-Larah

Mike is a Software Engineer at endjin with over a decade of experience in solving business problems with technology. He has worked on a wide range of projects for clients across industries such as financial services, recruitment, and retail, with a strong focus on Azure technologies.