asp.net mvc:如何模拟 Url.Content(“~”)?
有人知道如何模拟 Url.Content("~")
吗?
(顺便说一句:我正在使用起订量)
anybody knows how to mock Url.Content("~")
?
(BTW: I'm using Moq)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您指的是控制器中的
Url
属性,该属性的类型为UrlHelper
。我们能够模拟它的唯一方法是提取一个 IUrlHelper 接口,并创建一个 UrlHelperWrapper 类,该类既实现它又包装本机 UrlHelper代码 > 类型。然后,我们在BaseController
上定义一个新属性,如下所示:这允许我们创建
IUrlHelper
的模拟并注入它们,但在默认情况下使用IUrlHelper
的实例代码>UrlHelperWrapper类。抱歉,这很啰嗦,但正如您所发现的,否则这是一个问题。但是,它确实不需要更改任何Url.Action
以及控制器中的类似调用。这是接口:
我不会费心给您 UrlHelperWrapper 的定义 - 它实际上只是一个实现此功能的愚蠢包装器,并将所有调用传递给
UrlHelper
。You are referring to the
Url
property in the controllers, I presume, which is of typeUrlHelper
. The only way we have been able to mock this is to extract anIUrlHelper
interface, and create aUrlHelperWrapper
class that both implements it and wraps the nativeUrlHelper
type. We then define a new property on ourBaseController
like so:This allows us to create mocks of
IUrlHelper
and inject them, but in the default case to use an instance of ourUrlHelperWrapper
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 yourUrl.Action
and similar calls in your controllers.Here's the interface:
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 toUrlHelper
.使用 NUnit 中的 ForPartsOf(部分 subs 和测试间谍) 获得自由
Fell free with ForPartsOf (Partial subs and test spies) in NUnit
我知道此内容已过时,但这就是我现在的做法:
IContentResolver.cs
ContentResolver.cs
ContentResolverTests.cs
I know this content is old, but this is how I do it now:
IContentResolver.cs
ContentResolver.cs
ContentResolverTests.cs
这是我的一个方法,它模拟 url.content (并将 IsAjaxRequest() 设置为 true)
this is a method of mine that mocks the url.content (and also sets the IsAjaxRequest() to true)