asp.net-mvc - asp.net mvc : how to mock Url. 内容 ("~")?

标签 asp.net-mvc unit-testing moq

任何人都知道如何模拟Url.Content("~") ?

(顺便说一句:我正在使用最小起订量)

最佳答案

您指的是Url我认为 Controller 中的属性是 UrlHelper 类型.我们能够模拟它的唯一方法是提取 IUrlHelper接口(interface),并创建一个UrlHelperWrapper既实现它又包装原生的类 UrlHelper类型。然后我们在 BaseController 上定义一个新属性。像这样:

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

这允许我们创建 IUrlHelper 的模拟。并注入(inject)它们,但在默认情况下使用我们的 UrlHelperWrapper 的实例类(class)。抱歉,这很啰嗦,但是正如您所发现的那样,否则这是一个问题。但是,它确实可以插入,而无需更改您的任何 Url.Action以及 Controller 中的类似调用。

这是界面:
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);
}

我不会费心给你 UrlHelperWrapper 的定义。 - 它实际上只是一个实现这一点的愚蠢包装器,并将所有调用传递给 UrlHelper .

关于asp.net-mvc - asp.net mvc : how to mock Url. 内容 ("~")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092081/

相关文章:

c# - Lucene.Net IndexWriter 无法加载文件错误?

c# - 为什么我预期的空对象不为空?

c# - 如何模拟特定函数

java - 如何模拟返回文件的方法

c# - 试图理解 MockSequence

c# - 模拟存储库返回 null

asp.net-mvc - ASP.NET MVC 输出缓存属性 : do not cache if a parameter is set?

c# - 如何使用反射通过其属性值之一获取属性名称或如何获取当前正在验证的数据属性的属性信息?

c++ - GoogleMock:如何保存要在模拟的下一次调用中使用的参数

python - 循环 : 1 test per iteration 中的 assertRaises