So myself and my buddy Jamie decided to quickly start working on a web app powered by Asp.NET MVC4 and Web API. I'm working on most of the back end and I really wanted to have a good Test-Driven-Development environment in Visual Studio (2013). Naturally I wanted to use the VS Test Explorer window to mimick the client calls to each API to validate my dev work.

After searching around a bit I found a few handy blog posts like this one from one of my colleagues at Microsoft. This post is great because it shows you how to test your WebApi completley in-process without having to use the networking stack. However I like to use the in-box Visual Studio tools rather than xUnit that this blog had.

To give you a background on my setup I have a web app called GiftMe. Here's my Visual Studio solution setup:

Giftme.sln

>GiftMe.csproj (The ASP.NET web api)

>GIftMe.Tests (A unit test framework library)

So I have my Web API controller in the GIftMe.csproj project which looks something like this:

To my surprise, I kept getting HTTP404 errors back from the request. After a while it I was wondering how Web API 'magically' fond your controller to route http messages. It turns out that it looks at all loaded modules in the process for anything that extends the ApiController type. It also turned out that if you make no reference to the actual controller, the .NET runtime loader will never load the DLL with the Web API controllers (even though you reference GiftMe.dll) unless you actually use something in that DLL.

How do you fix this? Well for this example if you just reference the type AuthenticationController anywhere you'll force the runtime to load GiftMe.dll allowing the in-proc sever to find your Web API. I recommend putting this in the class initializer for the test library like so:

And viola! Your controller should be able to handle the request from the in-proc server and you have a nice, integrated test-driven-development environment for all of your web apis organized in a sane way.