如何从模拟控制器ActionResult方法获取模型

时间:2014-03-05 17:53:09

标签: c# controller moq

我有以下内容:

        SiteViewModel testForm = new SiteViewModel
        {
            SiteID = 0,
            DateCreated = DateTime.Now,
            Name = "A",
        };

        SiteController controller = new SiteController(mockSiteRepository.Object);

        //// Act
        SiteViewModel result = controller.Edit(testForm); // This will not work because Edit is an ActionResult... but I want to get the model that comes out the end of the ActionResult

如何从ActionResult方法获取模型,以便我可以对其进行测试?

1 个答案:

答案 0 :(得分:0)

您必须将ActionResult投射到ViewResult。然后,您可以访问Model属性。

// Act
var result = controller.Edit(testForm);

// Assert
var viewResult = result as ViewResult;
Assert.That(viewResult, Is.Not.Null);

var model = viewResult.Model as SiteViewModel;
Assert.That(model, Is.Not.Null);

// do your other assertions.

有关不同ActionResult类型的有趣讨论,请参阅this answer

如果您的Edit操作只返回ViewResult,那么您可以更改其方法签名以指示该操作。我不建议这样做,因为它会使你的代码更脆弱,例如,如果你想在将来改变Action的行为。