How to check ASP.Net MVC View?

I want to write unit test to make sure the returned view is correct.

My plan is to write a test that first calls the controller, and then calls the ActionResult method, which I plan to test I thought I could write something like

Controller controller = new HomeController(); var actionresult = controller.Index(); Assert.False(actionresult.ToString(), String.Empty); 

which will then allow me to analyze the resultult action for the test value. However, I cannot directly create the public ActionResult Index() method.

How to do it?

+4
source share
2 answers

Here is an example from Professional ASP.NET MVC 1.0 (book):

 [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 do not return the explicit view in your controller method, i.e. do the following:

 Return(View("About")); 

Not this:

 Return(View()); 

Or the test fails. You will need to do this only if your method ever returns more than one view, otherwise you should return the implicit view in any case and not bother testing the framework.

+1
source

Test assistants at MVCContrib will help you here.

 ViewResult result = controller.Index().AssertViewRendered().ForView("Blah"); 
+4
source

Source: https://habr.com/ru/post/1285963/


All Articles