本文介绍了当返回类型为 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); }测试方法可以访问Model属性,只有返回类型为ViewResult.在上面的代码中,我使用了 RedirectToAction 所以这个动作的返回类型不能是 ViewResult.
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?
推荐答案这是我的小例子:
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 后,您可以将其转换为:
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) { //... } }更多推荐
当返回类型为 ActionResult 时,如何对操作进行单元测试?
发布评论