1

我正在尝试使用 MvcContrib TestHelper 的静态OutBoundUrl类测试 MVC 区域中操作方法的出站 URL。这是我所拥有的:

OutBoundUrl.Of<ErrorsController>(action => action.NotFound())
    .ShouldMapToUrl("/errors/404");

我进入源代码,发现UrlHelper出站 URL 返回 null。基本上它会创建一个新的 UrlHelper 并将任务委托给UrlHelper.Action(action, controller, routeValues).

调用时,routeValues不包含任何内容(操作方法不接受任何参数)。这是一个错误吗?还是我需要做一些额外的事情来使这项工作与区域一起工作?在单元测试中,以下行位于上述行之前,因此我的路由已注册(UrlHelper.RouteCollection包含 100 多个路由)。

"~/errors/404".WithMethod(HttpVerbs.Get)
    .ShouldMapTo<ErrorsController>(action => action.NotFound());

路线没有命名,我也不想命名,所以请不要建议我使用该OfRouteNamed方法。

更新

我做了一个可以工作的扩展方法,除了一件事。该OutBoundController Of<TController>方法具有以下代码:

var methodCall = ((MethodCallExpression)action.Body);
var methodName = methodCall.Method.Name;

该方法中有类似但截然不同的代码RouteTestingExtensions ShouldMapTo<TController>

var methodCall = (MethodCallExpression) action.Body;
// this line is not important
string expectedAction = methodCall.Method.ActionName();

如果您使用,ActionName()扩展方法会很棒ActionNameAttributes

/// <summary>
/// Will return the name of the action specified in the ActionNameAttribute 
/// for a method if it has an ActionNameAttribute.
/// Will return the name of the method otherwise.
/// </summary>
/// <param name="method"></param>
/// <returns></returns>
public static string ActionName(this MethodInfo method)
{
    if (method.IsDecoratedWith<ActionNameAttribute>()) 
        return method.GetAttribute<ActionNameAttribute>().Name;

    return method.Name;
}

回到问题......这是设计使然,如果是这样,为什么?OutBoundUrl不使用扩展的事实.ActionName()是让我无法编写扩展方法来为用[ActionName].

4

0 回答 0