本文介绍了使用MVCContrib TestHelper错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在落实第二个答案的一个,我收到一个错误。

While trying to implement the second answer to a previous question, I am receiving an error.

我已经实现的方法只是作为交节目和前三正常工作。第四个(HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successfully_Delete)给出了这样的错误:找不到在结果的Values​​集合命名为控制器参数

I have implemented the methods just as the post shows, and the first three work properly. The fourth one (HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successfully_Delete) gives this error: Could not find a parameter named 'controller' in the result's Values collection.

如果我改变code为:

If I change the code to:

actual 
    .AssertActionRedirect() 
    .ToAction("Index");

它工作正常,但我不喜欢魔串在那里,preFER使用所使用的其他海报拉姆达方法。

it works properly, but I don't like the "magic string" in there and prefer to use the lambda method that the other poster used.

我的控制器方法是这样的:

My controller method looks like this:

    [HttpPost]
    public ActionResult Delete(State model)
    {
        try
        {
            if( model == null )
            {
                return View( model );
            }

            _stateService.Delete( model );

            return RedirectToAction("Index");
        }
        catch
        {
            return View( model );
        }
    }

我在做什么错了?

What am I doing wrong?

推荐答案

MVCContrib.TestHelper 希望您能在重定向时指定控制器名称的删除动作:

MVCContrib.TestHelper expects you to specify the controller name when redirecting in the Delete action:

return RedirectToAction("Index", "Home");

然后,你将能够使用强类型的断言:

Then you would be able to use the strongly typed assertion:

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

这将允许您离开重定向的是:

which would allow you to leave the redirect as is:

return RedirectToAction("Index");

和测试的结果是这样的:

and test the result like this:

actual
    .AssertActionRedirect()
    .ToActionCustom<HomeController>(c => c.Index());

这篇关于使用MVCContrib TestHelper错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:16