Reputation:
I'm having problems retrieving the route url from controller.RouteUrl(routeName) method. Here is my code for mocking the urls in my test method:
//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);
...
where the method SetFakeUrlHelper is defined as:
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);
}
and the method FakeHttpContext is defined as:
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;
}
The problem is that when in my controller action I call
public ActionResult MyAction()
{
...
var callBackUrl = Url.RouteUrl("AdminPaymentResult");
...
}
I get an empty string instead of "Payment/Result" as expected... Thanks in advance
Upvotes: 1
Views: 1417
Reputation: 1038770
You should mock the ApplyAppPathModifier
method on the response
which is internally used by the UrlHelper
. So just add the following line inside your FakeHttpContext
method and you will be good to go:
response
.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
.Returns<string>(x => x);
Upvotes: 3