Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc: how to mock Url.Content("~")?

anybody knows how to mock Url.Content("~") ?

(BTW: I'm using Moq)

like image 563
Omu Avatar asked Dec 22 '22 06:12

Omu


1 Answers

You are referring to the Url property in the controllers, I presume, which is of type UrlHelper. The only way we have been able to mock this is to extract an IUrlHelper interface, and create a UrlHelperWrapper class that both implements it and wraps the native UrlHelper type. We then define a new property on our BaseController like so:

public new IUrlHelper Url
{
    get { return _urlHelper; }
    set { _urlHelper = value; }
}

This allows us to create mocks of IUrlHelper and inject them, but in the default case to use an instance of our UrlHelperWrapper class. Sorry it's long winded, but as you have discovered, it's a problem otherwise. It does, however, drop in without the need to change any of your Url.Action and similar calls in your controllers.

Here's the interface:

public interface IUrlHelper
{
    string Action(string actionName);
    string Action(string actionName, object routeValues);
    string Action(string actionName, string controllerName);
    string Action(string actionName, RouteValueDictionary routeValues);
    string Action(string actionName, string controllerName, object routeValues);
    string Action(string actionName, string controllerName, RouteValueDictionary routeValues);
    string Action(string actionName, string controllerName, object routeValues, string protocol);
    string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName);
    string Content(string contentPath);
    string Encode(string url);
    string RouteUrl(object routeValues);
    string RouteUrl(string routeName);
    string RouteUrl(RouteValueDictionary routeValues);
    string RouteUrl(string routeName, object routeValues);
    string RouteUrl(string routeName, RouteValueDictionary routeValues);
    string RouteUrl(string routeName, object routeValues, string protocol);
    string RouteUrl(string routeName, RouteValueDictionary routeValues, string protocol, string hostName);
}

I won't bother giving you the definition of UrlHelperWrapper - it really is just a dumb wrapper that implements this, and passes all calls through to UrlHelper.

like image 88
David M Avatar answered Dec 29 '22 09:12

David M