views:

45

answers:

2

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

+1  A: 

@Miau, I've seen a couple of questions on the same topic already Can we unit test View (‘V’) of MVC? and Unit Testing the Views? You can also look at this post from Steve Sanderson's blog.

Regards.

uvita
+1  A: 

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