views:

44

answers:

2

Hi,

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?

+2  A: 
// Arrange
var c = new MyController();

//Act
var result = c.Index(null,null);
var model = result.ViewData.Model; 

//Assert
Assert("model is what you want");

Kindness, Dan

Daniel Elliott
it's in the viewdata! Thanks, didn't look there.
Michel
+1  A: 

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");
Darin Dimitrov