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

为君一笑 提交于 2019-12-28 05:37:08

问题


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 Model properties, only when return type is ViewResult. In above code, I have used RedirectToAction so return type of this action can not be ViewResult.

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


回答1:


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:

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



回答2:


Please note that

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

has been deprecated.

The new syntax is

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



回答3:


Try this code:

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


来源:https://stackoverflow.com/questions/18865257/how-to-unit-test-an-action-when-return-type-is-actionresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!