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).

Azure Weekly is a summary of the week's top Microsoft Azure news from AI to Availability Zones. Keep on top of all the latest Azure developments!

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.

Programming C# 12 Book, by Ian Griffiths, published by O'Reilly Media, is now available to buy.

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

@MikeLarah

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.