How to get the Model from an ActionResult?

前端 未结 4 953
既然无缘
既然无缘 2020-12-30 23:25

I\'m writing a unit test and I call an action method like this

var result = controller.Action(123);

result is ActionResult and

4条回答
  •  独厮守ぢ
    2020-12-30 23:44

    In my version of ASP.NET MVC there is no Action method on Controller. However, if you meant the View method, here's how you can unit test that the result contains the correct model.

    First of all, if you only return ViewResult from a particular Action, declare the method as returning ViewResult instead of ActionResult.

    As an example, consider this Index action

    public ViewResult Index()
    {
        return this.View(this.userViewModelService.GetUsers());
    }
    

    you can get to the model as easily as this

    var result = sut.Index().ViewData.Model;
    

    If your method signature's return type is ActionResult instead of ViewResult, you will need to cast it to ViewResult first.

提交回复
热议问题