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:

http://www.asp.net/mvc/tutorials/older-versions/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

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:

http://visualstudiogallery.msdn.microsoft.com/7f3bdc82-f418-41aa-ad15-f1d6f89df47a

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:

http://razorgenerator.codeplex.com/

http://nuget.org/packages/RazorGenerator.Mvc

http://nuget.org/packages/RazorGenerator.Testing

http://blog.davidebbo.com/search/label/RazorGenerator

6. Last but not the least, QUnit can help you to test the JavaScript and JQuery codes written within your view files:

http://nuget.org/packages/QUnit-MVC

http://www.dotnetcurry.com/ShowArticle.aspx?ID=400