Tools and Mechanisms available for Unit Test on ASP.Net MVC (Razor) Application
One of the great things about ASP.Net MVC is easy implementation of Unit Tests. In fact while you start with an ASP.Net MVC application you get an option to create a Unit Test Project along with the MVC Project.
But for a regular ASP.Net developer, ASP.Net MVC and especially the Razor View Engine (in MVC3/MVC4) sometimes confusing and they get more confused when they are asked to create Unit Tests on top of it. This article describes some tools and mechanisms that can help the developers creating successful Unit Test on their MVC applications.
1 .Let’s first talk about the built in Unit Test Project Template available within Visual Studio. A good example of how to use it for MVC can be found here:
It’s possible to use this type of Unit Test to test the output of different controller methods. As given in the example, it can be the name of the view got returned, Redirect Action or you can even check the data that is available within the Model associated with the View.
2. Similar but arguably better option can be using NuGet’s NUnit Template:
NUnit has a mocking framework built-in. Also it can run beyond IDE. Which is helpful if you are using a Non-MS Build Server.
3. In both the above cases, usage of ReSharper (http://www.jetbrains.com/resharper/download/) will give additional advantages.
4. You can also take advantage of an independent mocking framework like Moq (http://code.google.com/p/moq/). Here is one such example: http://www.codethinked.com/Simplified-Aspnet-MVC-Controller-Testing-with-Moq.
5. All the tools we discussed above will give you options to test methods in Controller classes. Sometimes, you may need to Test a View or Partial View that is generated as output. NuGet’s RazorGenerator can help you do so. RazorGenerator allows processing Razor files at design time instead of runtime. Here are the links for RazorGenerator: