C# 当返回类型为 ActionResult 时,如何对操作进行单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18865257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:27:38  来源:igfitidea点击:

How to unit-test an action, when return type is ActionResult?

c#unit-testingasp.net-mvc-4tdd

提问by Abhijeet

I have written unit test for following action.

我已经为以下操作编写了单元测试。

[HttpPost]
public ActionResult/*ViewResult*/ Create(MyViewModel vm)
{
    if (ModelState.IsValid)
    {
        //Do something...
        return RedirectToAction("Index");
    }

    return View(vm);
}

Test method can access Modelproperties, only when return type is ViewResult. In above code, I have used RedirectToActionso return type of this action can not be ViewResult.

测试方法可以访问Model属性,只有当返回类型为ViewResult. 在上面的代码中,我使用了RedirectToAction所以这个动作的返回类型不能是ViewResult.

In such scenario how do you unit-test an action?

在这种情况下,您如何对操作进行单元测试?

采纳答案by Péter

So here is my little example:

所以这是我的小例子:

public ActionResult Index(int id)
{
  if (1 != id)
  {
    return RedirectToAction("asd");
  }
  return View();
}

And the tests:

和测试:

[TestMethod]
public void TestMethod1()
{
  HomeController homeController = new HomeController();
  ActionResult result = homeController.Index(10);
  Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult));
  RedirectToRouteResult routeResult = result as RedirectToRouteResult;
  Assert.AreEqual(routeResult.RouteValues["action"], "asd");
}

[TestMethod]
public void TestMethod2()
{
  HomeController homeController = new HomeController();
  ActionResult result = homeController.Index(1);
  Assert.IsInstanceOfType(result, typeof(ViewResult));
}

Edit:
Once you verified that the result type is ViewResut you can cast to it:

编辑:
验证结果类型为 ViewResut 后,您可以将其转换为:

ViewResult vResult = result as ViewResult;
if(vResult != null)
{
  Assert.IsInstanceOfType(vResult.Model, typeof(YourModelType));
  YourModelType model = vResult.Model as YourModelType;
  if(model != null)
  {
    //...
  }
}

回答by Esteban Chi

Please note that

请注意

Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult)); 

has been deprecated.

已被弃用。

The new syntax is

新语法是

Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());

回答by ANKIT SINGH

Try this code:

试试这个代码:

dynamic result=objectController.Index();
Assert.AreEqual("Index",result.ViewName);