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

编程入门 行业动态 更新时间:2024-10-21 18:31:26
本文介绍了当返回类型为 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 时,如何对操作进行单元测试?

本文发布于:2023-11-11 07:42:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577783.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   类型   操作   ActionResult

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!