我在从controller.RouteUrl(routeName)方法检索路由网址时遇到问题。 这是我在我的测试方法中模拟网址的代码:
//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");
...
}
我得到一个空字符串而不是预期的“付款/结果”... 提前致谢
答案 0 :(得分:4)
您应该模仿response
内部使用的UrlHelper
上的ApplyAppPathModifier
方法。因此,只需在FakeHttpContext
方法中添加以下行,您就可以了:
response
.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
.Returns<string>(x => x);