Share via


How would I test a WebAPI controller

Kind of related to my previous post, this article on how to test ASP.Net WebAPI controllers made me think. As you can see from the article it is fairly easy to get your controller under test, but it does take some work to get everything setup properly. And I have never tested my WebAPI controllers like that.

First of all my experience is that since WebAPI provides an MVC model it is very tempting to write your application logic as controllers. I mean, that is what MVC is all about. However almost all MVC and MVVM frameworks I've been exposed to end up with some dependency that is very specific to the target application (ex: HttpResponseMessage in WebApi). I like my application logic to be 100% isolated from presentation which means that the controller of WebAPI is not the place for my application logic. The only thing the WebAPI controller should do in my opinion is to translate between HTTP and my application logic.

This creates a situation where I can test my application logic easily and if necessary reuse it in different types of applications (WebAPI vs Console apps vs WinForm apps). The WebAPI layer then becomes so thin that I can feel confident that it works even without any unit tests. That is how I would do it... However if I have some extra time to spend on writing unit tests, adding a test or two that verifies the conversion between HTTP and my application logic is not so bad either and the article mentioned above is a good help. But that would be icing on the cake.

Comments

  • Anonymous
    June 10, 2013
    nice!