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

时间:2013-09-18 06:26:12

标签: c# unit-testing asp.net-mvc-4 tdd

我已经为下面的行动编写了单元测试。

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

    return View(vm);
}

只有当返回类型为Model时,测试方法才能访问ViewResult属性。在上面的代码中,我使用了RedirectToAction,因此此操作的返回类型不能是ViewResult

在这种情况下,你如何对行动进行单元测试?

3 个答案:

答案 0 :(得分:67)

所以这是我的小例子:

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

测试:

[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));
}

修改
验证结果类型为ViewResut后,您可以投射到它:

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

答案 1 :(得分:9)

请注意

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

已被弃用。

新语法是

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

答案 2 :(得分:0)

试试这段代码:

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