gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:02:07 28 4
gpt4 key购买 nike

我已经为后续操作编写了单元测试。

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

return View(vm);
}

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

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

最佳答案

这是我的小例子:

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)
{
//...
}
}

关于c# - 当返回类型为 ActionResult 时,如何对操作进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865257/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com