在尝试实施第二个答案时上一个问题 https://stackoverflow.com/questions/2887121/why-does-this-asp-net-mvc-unit-test-fail,我收到错误。
我已经按照帖子所示实现了这些方法,前三个工作正常。第四个 (HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successively_Delete) 给出此错误:在结果的 Values 集合中找不到名为“controller”的参数。
如果我将代码更改为:
actual
.AssertActionRedirect()
.ToAction("Index");
它工作正常,但我不喜欢其中的“魔术字符串”,并且更喜欢使用其他海报使用的 lambda 方法。
我的控制器方法如下所示:
[HttpPost]
public ActionResult Delete(State model)
{
try
{
if( model == null )
{
return View( model );
}
_stateService.Delete( model );
return RedirectToAction("Index");
}
catch
{
return View( model );
}
}
我究竟做错了什么?
MVCContrib.TestHelper
期望您在重定向时指定控制器名称Delete
action:
return RedirectToAction("Index", "Home");
然后您就可以使用强类型断言:
actual
.AssertActionRedirect()
.ToAction<HomeController>(c => c.Index());
另一种选择是自己编写ToActionCustom
扩展方法:
public static class TestHelperExtensions
{
public static RedirectToRouteResult ToActionCustom<TController>(
this RedirectToRouteResult result,
Expression<Action<TController>> action
) where TController : IController
{
var body = (MethodCallExpression)action.Body;
var name = body.Method.Name;
return result.ToAction(name);
}
}
这将允许您按原样保留重定向:
return RedirectToAction("Index");
并像这样测试结果:
actual
.AssertActionRedirect()
.ToActionCustom<HomeController>(c => c.Index());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)