Testing View in MVC
In this article, I am going to demonstrates how to test the view returned by a controller action.
You can know how to test the view returned by a controller action, how to test the View Data returned by a controller action, and how to test whether or not one controller action redirects you to a second controller action.
Here I am going to create Unit Test project in MVC:
Open Microsoft Visual Studio à New Project à ASP.NET MVC3 Web Application.
Select Internet Application from New ASP.NET MVC3 Project template and select Visual Studio Unit Test for the Test Framework.
Delete pre-existence file from a Controller folder that exists in .Tests extension.
The ProductController contains two action methods named Index() and Details(). Both action methods return a view. The Details() action accepts a parameter named Id.
public class ProductController : Controller
public ActionResult Index()
throw new NotImplementedException();
public ActionResult Details(int Id)
After creating a Controller, create a unit test for the controller:
Right click on the Controller folder à Add à New Test.
Select Basic Unit Test from Add New Test template.
In ProductControllerTest.cs we test that whether ProductController returns the right view or not. We want to make sure that when the ProductController.Details() action is invoked, the Details view is returned. The test class in Listing 2 contains a unit test for testing the view returned by the ProductController.Details() action.
public class ProductControllerTest
public void TestDetailsView()
var controller = new ProductController();
var result = controller.Details(2) as ViewResult;
If ProductController returns the matched View the result will come Passed else the result will be Aborted. Our Product controller return the matched View that’s why Result comes Passed.
The above process indicates how to test the View returned by the Controller action with the help of Visual Studio Unit Test project.