代码之家  ›  专栏  ›  技术社区  ›  Omu

如何从ActionResult中获取模型?

  •  21
  • Omu  · 技术社区  · 15 年前

    我正在编写一个单元测试,我调用了这样的操作方法

    var result = controller.Action(123);
    

    结果是 ActionResult 我得找个模特儿,有人知道怎么做吗?

    4 回复  |  直到 8 年前
        1
  •  31
  •   Community CDub    8 年前

    在我的ASP.NET MVC版本中,没有 Action 控制器上的方法。但是,如果你的意思是 View 方法,下面介绍如何对结果包含正确模型的单元测试。

    首先,如果只返回特定操作的viewResult,则将该方法声明为 returning ViewResult instead of ActionResult .

    例如,考虑这个索引操作

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

    你可以像这样轻易地找到模型

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

    如果方法签名的返回类型是actionresult而不是viewresult,则需要首先将其强制转换为viewresult。

        2
  •  16
  •   Jeremy Thompson    8 年前

    我们将下面的部分放在testsbase.cs中,允许在测试a la中输入模型

    ActionResult actionResult = ContextGet<ActionResult>();
    var model = ModelFromActionResult<SomeViewModelClass>(actionResult);
    

    ModelFromActionResult…

    public T ModelFromActionResult<T>(ActionResult actionResult)
    {
        object model;
        if (actionResult.GetType() == typeof(ViewResult))
        {
            ViewResult viewResult = (ViewResult)actionResult;
            model = viewResult.Model;
        }
        else if (actionResult.GetType() == typeof(PartialViewResult))
        {
            PartialViewResult partialViewResult = (PartialViewResult)actionResult;
            model = partialViewResult.Model;
        }
        else
        {
            throw new InvalidOperationException(string.Format("Actionresult of type {0} is not supported by ModelFromResult extractor.", actionResult.GetType()));
        }
        T typedModel = (T)model;
        return typedModel;
    }
    

    使用索引页和列表的示例:

    var actionResult = controller.Index();
    var model = ModelFromActionResult<List<TheModel>>((ActionResult)actionResult.Result);
    
        3
  •  10
  •   Omu    15 年前

    考虑a=actionResult;

    ViewResult p = (ViewResult)a;
    p.ViewData.Model
    
        4
  •  2
  •   Chris Marisic    11 年前

    在.net4中,这有点欺骗,但却是一种非常简单的方法。

    dynamic result = controller.Action(123);
    
    result.Model
    

    今天在单元测试中使用了这个。可能值得做一些健康检查,比如:

    Assert.IsType<ViewResult>(result); 
    Assert.IsType<MyModel>(result.Model);
    
    Assert.Equal(123, result.Model.Id);
    

    如果结果将是视图或部分结果(取决于输入),则可以跳过第一个结果。