Thursday, April 21, 2016

Unit Testing a loading of correct View in MVC




[TestMethod]
public void AboutReturnsAboutView()
{
     HomeController controller = new HomeController();
     ViewResult result = controller.About() as ViewResult;

     Assert.AreEqual("About", result.ViewName);
}
Note that this will fail if you don't return an explicit view in your controller method, i.e. do this:


     Return(View("About"));
not this:


     Return(View());
Or the test won't pass. You should only need to do this if your method will ever return more than one view, otherwise you should return an implicit view anyway and not bother testing the framework.


Refer: Professional ASP.NET MVC 1.0 (book):

No comments: