asp.net mvc:如何模拟Url.Content(“〜")? [英] asp.net mvc: how to mock Url.Content("~")?

查看:185
本文介绍了asp.net mvc:如何模拟Url.Content(“〜")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何嘲笑Url.Content("~")吗?

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

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

(BTW: I'm using Moq)

推荐答案

我假设您是指控制器中的Url属性,类型为UrlHelper.我们能够模拟的唯一方法是提取一个IUrlHelper接口,并创建一个实现和包装本机UrlHelper类型的UrlHelperWrapper类.然后,我们在BaseController上定义一个新属性,如下所示:

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; }
}

这允许我们创建IUrlHelper的模拟并注入它们,但是在默认情况下使用UrlHelperWrapper类的实例.抱歉,它已经long绕了,但是正如您所发现的,否则这是一个问题.但是,它确实可以插入而无需更改控制器中的任何Url.Action和类似调用.

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.

以下是界面:

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.

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.

这篇关于asp.net mvc:如何模拟Url.Content(“〜")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆