[英]How to unit-test an action, when return type is ActionResult?
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
. 只有当返回类型为
ViewResult
时,测试方法才能访问Model
属性。 In above code, I have used RedirectToAction
so return type of this action can not be ViewResult
. 在上面的代码中,我使用了
RedirectToAction
因此这个动作的返回类型不能是ViewResult
。
In such scenario how do you unit-test an action? 在这种情况下,您如何对一个动作进行单元测试?
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)
{
//...
}
}
Please note that 请注意
Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult));
has been deprecated. 已被弃用。
The new syntax is 新的语法是
Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
Try this code: 试试这段代码:
dynamic result=objectController.Index();
Assert.AreEqual("Index",result.ViewName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.