Reputation: 23625
i call a controller action in a unit test.
ViewResult result = c.Index(null,null) as ViewResult;
I cast the result to a ViewResult, because that is what i'm returning in the controller:
return View(model);
But how can i access this model variable in my unit test?
Upvotes: 4
Views: 4217
Reputation: 22867
// Arrange
var c = new MyController();
//Act
var result = c.Index(null,null);
var model = result.ViewData.Model;
//Assert
Assert("model is what you want");
Upvotes: 9
Reputation: 1038950
I would recommend you the excellent MVContrib test helper. Your test might look like this:
[TestMethod]
public void SomeTest()
{
// arrange
var p1 = "foo";
var p2 = "bar";
// act
var actual = controller.Index(p1, p2);
// assert
actual
.AssertViewRendered() // make sure the right view has been returned
.WithViewData<SomeViewData>(); // make sure the view data is of correct type
}
You can also assert on properties of the model
actual
.AssertViewRendered()
.WithViewData<SomeViewData>()
.SomeProp
.ShouldEqual("some expected value");
Upvotes: 4