【问题标题】:Error using MVCContrib TestHelper使用 MVCContrib TestHelper 时出错
【发布时间】:2010-06-04 20:29:17
【问题描述】:

在尝试实现previous question 的第二个答案时,我收到一个错误。

我已经按照帖子显示的方法实现了这些方法,并且前三个工作正常。第四个(HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successfully_Delete)给出了这个错误:在结果的值集合中找不到名为“控制器”的参数。

如果我将代码更改为:

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 );
        }
    }

我做错了什么?

【问题讨论】:

    标签: asp.net-mvc unit-testing rhino-mocks mvccontrib-testhelper


    【解决方案1】:

    MVCContrib.TestHelper 要求您在 Delete 操作中重定向时指定控制器名称:

    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());
    

    【讨论】:

    • 自定义扩展方法。我喜欢那个替代方案并且正在使用它。我不喜欢将控制器名称放在 RedirectToAction 中,这非常有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多