1

我在从 controller.RouteUrl(routeName) 方法检索路由 url 时遇到问题。这是我在测试方法中模拟 url 的代码:

//Arrange
...
//Mock routes
var routes = RouteTable.Routes;

routes.Clear();
routes.MapRoute(
    "AdminPaymentResult",      // Route name
    "Payment/Result");         // URL with parameters

routes.MapRoute(
    "AdminPaymentCancel",      // Route name
    "Payment/Cancel");         // URL with parameters

_controller.SetFakeUrlHelper(routes);
...

其中方法 SetFakeUrlHelper 定义为:

public static void SetFakeUrlHelper(this Controller controller, RouteCollection routes)
{
    var fakeHttpContext = FakeHttpContext();
    var requestContext = new RequestContext(fakeHttpContext, new RouteData());
    controller.Url = new UrlHelper(requestContext, routes);
}

并且 FakeHttpContext 方法定义为:

public static HttpContextBase FakeHttpContext()
{
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    var server = new Mock<HttpServerUtilityBase>();

    var context = new Mock<HttpContextBase>();

    context.Setup(ctx => ctx.Request).Returns(request.Object);
    context.Setup(ctx => ctx.Response).Returns(response.Object);
    context.Setup(ctx => ctx.Session).Returns(session.Object);
    context.Setup(ctx => ctx.Server).Returns(server.Object);

    return context.Object;
}

问题是当我在我的控制器操作中调用

public ActionResult MyAction()
{
    ...
    var callBackUrl = Url.RouteUrl("AdminPaymentResult");
    ...
}

我得到一个空字符串而不是预期的“付款/结果”......提前致谢

4

1 回答 1

3

您应该模拟.内部使用的ApplyAppPathModifier方法。因此,只需在您的方法中添加以下行,您就可以开始了:responseUrlHelperFakeHttpContext

response
    .Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
    .Returns<string>(x => x);
于 2012-06-13T09:38:39.220 回答