Unit Testing ASP.Net MVC 4 apps thoroughly

Ben Lesh picture Ben Lesh · Feb 10, 2012 · Viewed 14.5k times · Source

I realize this is a duplicate of about 20 different posts, but none of them are specific to MVC4, and none that I've seen really answer all of my questions. So far my first foray into the world of TDD has been frustrating to say the least. Most of what I've tried to do seems incompatible with MVC 4 or next to impossible without using poorly documented third party libraries I don't quite understand yet.

What I want to be able to do, is write a tests that will test my Controller Actions, The Model they're passing and The View the action is sending the model to. I want to test if the view exists, I want to test if the model being passed is the right type for the view, I'd like some way to test if it will process properly. I also want to be able to test my routes. And testing Authentication filters?

I want a way to unit test ASP.Net MVC that will leave very little to chance.

Testing the Model output of an Action seems easy enough, but testing the views has been next to impossible.

So here's my list of questions:

  1. Once I test the action and get the action result, how do I test to see if the view it wants exists?
  2. How do I test my routes?
  3. How can I test to be sure my views are being processed properly?
  4. What is really "best practice" for THOROUGH unit testing of ASP.Net MVC 4?
  5. How do I unit test forms authentication?
  6. How do I unit test Action Filters?

I'd prefer to use the built in Visual Studio test projects, but if I must use NUnit, I must. I just need to make sure it gets done properly.

Thank you in advance for your responses.

EDIT: I also couldn't get NUnit working with my MVC4 app because of some incompatibly with the version of .NET one of the assemblies was compiled in.

Answer

Rob Rodi picture Rob Rodi · Mar 29, 2012
  1. Making sure a view exists
  2. http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx/
  3. http://blog.davidebbo.com/2011/06/unit-test-your-mvc-views-using-razor.html
  4. see below
  5. How can I unit test my ASP.NET MVC controller that uses FormsAuthentication?
  6. How-to test action filters in ASP.NET MVC?

no. 4: This is a hard question. How does one test anything thoroughly? Personally, I don't really test the views, other than with the 3 major browsers and my two eyes, as it's hard to test a website and all it's components without actually using it. You have JavaScript firing, CSS stylizing, and it looks different across different browsers. So, to me, it seems like testing the view that thoroughly is a minor part of the overall usability of your site. If you're developing a simple table based report of financial data, test that data hard. If your view is a the base for a fancy Ajax site, maybe don't test the HTML so much as the experience. I know it's not an easy, cut-and-dry answer, but the acceptable level of coverage always involves trade offs.