40

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

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

    return View(vm);
}

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

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

4

3 回答 3

72

所以这是我的小例子:

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)
  {
    //...
  }
}
于 2013-09-18T06:49:55.407 回答
13

请注意

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

已被弃用。

新语法是

Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
于 2015-03-12T20:16:37.883 回答
-2

试试这个代码:

dynamic result=objectController.Index();
Assert.AreEqual("Index",result.ViewName);
于 2016-08-12T08:37:56.487 回答