Alex Rivera | Logout

unit testing asp mvc view

Asked 2010-02-22T22:22:19.290
25

How can i unit test the view of an ASP MVC application?

I have tried the mvc contrib test helper...

 _controller.Index().AssertViewRendered();

but this doesn't actually test the view.

for example i can happily insert some bogus code in the view, and get the dreaded yellow screen of death, without my unit test ever knowing about it.

Is there any estabilished method of doing this? Do i need a mock out the view engine? Does mvccontrib cater to this?

I would have thought this would be a very common requirement, but i can't find much about it!

Thanks

EDIT What i'm really after is compile time checking, to ensure that model changes don't impact the view.

this question contained the instructions to enable build time view compilation which is sufficient for me for now. Compile Views in ASP.NET MVC

Edit
Report

1 Answer

1

It's fairly easy to test the view in an ASP.NET MVC page.

I walk you through step-by-step in a YouTube video. Here's an outline of the required steps:

  1. You need to create a unit test in the controller. This allows to to easily call the rendered result. For example:

    public ActionResult TestScenario()
    {
         // setup some models
         return View("Page", model);
    }
    
  2. Your unit test needs to call that ControllerAction, and verify the result. In ApprovalTests this would be:

    MvcApprovals.VerifyMvcPage(new MyController().TestScenario);
    

    This is all rather straight-forward in ApprovalTests (www.approvaltests.com or nuget).

answered 2012-05-07T23:35:53.303

Your Answer