6

HI there

I was wondering if there is a better way of testing that a view has rendered in MVC.

I was thinking perhaps I should render the view to a string but perhaps there are simpler methods?

Basically what I want to know if that the view for a given action has rendered without errors I m already testing the view model but I want to see that rendering the view giving a correct ViewData.Model works

roundcrisis
  • 17,276
  • 14
  • 60
  • 92
  • I've seen a couple of questions on the same topic already [Can we unit test View (ā€˜V’) of MVC?](https://stackoverflow.com/questions/1005819/can-we-unit-test-view-v-of-mvc) and [Unit Testing the Views?](https://stackoverflow.com/questions/151794/unit-testing-the-views) You can also look at [this](http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/) post from Steve Sanderson's blog. – uvita May 31 '10 at 15:51

2 Answers2

4

Use the MvcContrib TestHelpers library to perform assertions that a particular view is being returned from your action:

var sampleController = new SampleController();
sampleController.New().AssertViewRendered().ForView("New").WithViewData<SomeModel>();

To make assertions to ensure you are returning the correct data to the view, pull the model from the ActionResult:

var result = (ViewResult)sampleController.New();
((SomeModel)result.ViewData.Model).SomeProperty.ShouldNotBeNull();

This is as far as your unit testing should go.

For end-to-end automated functional/GUI testing you might want to think about using a tool like Selenium.

Steve Horn
  • 8,818
  • 11
  • 45
  • 60
0

You can enable views compilation for your project. In this way the project won't compile unless you fix the issues. Edit this line in the .csproj file:

<MvcBuildViews>false</MvcBuildViews> by using true instead of false

I you can also use ELMAH (install it view NuGet) and you can receive detailed errors by email (including YSOD).

Source

dre
  • 1,422
  • 3
  • 21
  • 31