我有以下内容:
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方法获取模型,以便我可以对其进行测试?
答案 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的行为。