如何在asp.net mvc unittest中从ViewResult获取模型?

时间:2010-04-22 10:33:01

标签: asp.net-mvc unit-testing

我在单元测试中调用控制器动作。

 ViewResult result = c.Index(null,null) as ViewResult;

我将结果转换为ViewResult,因为这是我在控制器中返回的内容:

return View(model);

但是我怎样才能在单元测试中访问这个模型变量?

2 个答案:

答案 0 :(得分:9)

// Arrange
var c = new MyController();

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

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

善, 丹

答案 1 :(得分:4)

我会向你推荐优秀的MVContrib test helper。您的测试可能如下所示:

[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
}

您还可以断言模型的属性

actual
    .AssertViewRendered()
    .WithViewData<SomeViewData>()
    .SomeProp
    .ShouldEqual("some expected value");