asp.net mvc:如何模拟 Url.Content(“~”)?

发布于 2024-08-17 23:49:16 字数 74 浏览 4 评论 0原文

有人知道如何模拟 Url.Content("~") 吗?

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

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

(BTW: I'm using Moq)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

余罪 2024-08-24 23:49:16

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

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

这允许我们创建 IUrlHelper 的模拟并注入它们,但在默认情况下使用 IUrlHelper 的实例代码>UrlHelperWrapper类。抱歉,这很啰嗦,但正如您所发现的,否则这是一个问题。但是,它确实不需要更改任何 Url.Action 以及控制器中的类似调用。

这是接口:

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

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.

笑梦风尘 2024-08-24 23:49:16
controller.Url = Substitute.ForPartsOf<UrlHelper>();
controller.Url.Content("~").Returns("path");

使用 NUnit 中的 ForPartsOf(部分 subs 和测试间谍) 获得自由

controller.Url = Substitute.ForPartsOf<UrlHelper>();
controller.Url.Content("~").Returns("path");

Fell free with ForPartsOf (Partial subs and test spies) in NUnit

日暮斜阳 2024-08-24 23:49:16

我知道此内容已过时,但这就是我现在的做法:

IContentResolver.cs

using System.Web;

namespace Web.Controllers
{
    public interface IContentResolver
    {
        string Resolve(string imageLocation, HttpRequestBase httpRequestBase);
    }
}

ContentResolver.cs

using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class ContentResolver : IContentResolver
    {
        public string Resolve(string imageLocation, HttpRequestBase httpRequestBase)
        {
            return new UrlHelper(httpRequestBase.RequestContext).Content(imageLocation);
        }
    }
}

ContentResolverTests.cs

using System.Web;
using System.Web.Routing;
using Web.Controllers;
using Moq;
using NUnit.Framework;

namespace Web.Tests.Controllers
{
    public class ContentResolverTests
    {
        [TestFixture]
        public class when_resolving_the_content_images
        {
            [Test]
            public void then_should_resolve_to_proper_location()
            {
                // Arrange
                var resolver = new ContentResolver();

                // Act
                var httpContextBase = new Mock<HttpContextBase>();
                var httpRequestBase = new Mock<HttpRequestBase>();

                httpContextBase.Setup(@base => @base.Request).Returns(httpRequestBase.Object);

                httpRequestBase.Setup(@base => @base.ApplicationPath).Returns("/Test");


                var requestContext = new Mock<RequestContext>();
                requestContext.SetupGet(context => context.HttpContext).Returns(httpContextBase.Object);

                httpRequestBase.SetupGet(@base => @base.RequestContext).Returns(requestContext.Object);

                var url = resolver.Resolve("~/Content/loading.gif", httpRequestBase.Object);

                // Assert
                Assert.That(url, Is.EqualTo("/Test/Content/loading.gif"));
            }
        } 
    }
}

I know this content is old, but this is how I do it now:

IContentResolver.cs

using System.Web;

namespace Web.Controllers
{
    public interface IContentResolver
    {
        string Resolve(string imageLocation, HttpRequestBase httpRequestBase);
    }
}

ContentResolver.cs

using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class ContentResolver : IContentResolver
    {
        public string Resolve(string imageLocation, HttpRequestBase httpRequestBase)
        {
            return new UrlHelper(httpRequestBase.RequestContext).Content(imageLocation);
        }
    }
}

ContentResolverTests.cs

using System.Web;
using System.Web.Routing;
using Web.Controllers;
using Moq;
using NUnit.Framework;

namespace Web.Tests.Controllers
{
    public class ContentResolverTests
    {
        [TestFixture]
        public class when_resolving_the_content_images
        {
            [Test]
            public void then_should_resolve_to_proper_location()
            {
                // Arrange
                var resolver = new ContentResolver();

                // Act
                var httpContextBase = new Mock<HttpContextBase>();
                var httpRequestBase = new Mock<HttpRequestBase>();

                httpContextBase.Setup(@base => @base.Request).Returns(httpRequestBase.Object);

                httpRequestBase.Setup(@base => @base.ApplicationPath).Returns("/Test");


                var requestContext = new Mock<RequestContext>();
                requestContext.SetupGet(context => context.HttpContext).Returns(httpContextBase.Object);

                httpRequestBase.SetupGet(@base => @base.RequestContext).Returns(requestContext.Object);

                var url = resolver.Resolve("~/Content/loading.gif", httpRequestBase.Object);

                // Assert
                Assert.That(url, Is.EqualTo("/Test/Content/loading.gif"));
            }
        } 
    }
}
小红帽 2024-08-24 23:49:16

这是我的一个方法,它模拟 url.content (并将 IsAjaxRequest() 设置为 true)

public static void SetContextWithAjaxRequestAndUrlContent(this BaseController controller)
{
    var routes = new RouteCollection();
    RouteConfigurator.RegisterRoutesTo(routes);


    var httpContextBase = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var respone = new Mock<HttpResponseBase>();


    httpContextBase.Setup(x => x.Request).Returns(request.Object);
    httpContextBase.Setup(x => x.Response).Returns(respone.Object);

    request.Setup(x => x.Form).Returns(new NameValueCollection());
    request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {{"X-Requested-With", "XMLHttpRequest"}});
    request.Setup(o => o.ApplicationPath).Returns("/Account");
    request.Setup(o => o["X-Requested-With"]).Returns("XMLHttpRequest");

    respone.Setup(o => o.ApplyAppPathModifier("/Account")).Returns("/Account");

    controller.ControllerContext = new ControllerContext(httpContextBase.Object, new RouteData(), controller);

    controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, new RouteData()), routes);
}

this is a method of mine that mocks the url.content (and also sets the IsAjaxRequest() to true)

public static void SetContextWithAjaxRequestAndUrlContent(this BaseController controller)
{
    var routes = new RouteCollection();
    RouteConfigurator.RegisterRoutesTo(routes);


    var httpContextBase = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var respone = new Mock<HttpResponseBase>();


    httpContextBase.Setup(x => x.Request).Returns(request.Object);
    httpContextBase.Setup(x => x.Response).Returns(respone.Object);

    request.Setup(x => x.Form).Returns(new NameValueCollection());
    request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {{"X-Requested-With", "XMLHttpRequest"}});
    request.Setup(o => o.ApplicationPath).Returns("/Account");
    request.Setup(o => o["X-Requested-With"]).Returns("XMLHttpRequest");

    respone.Setup(o => o.ApplyAppPathModifier("/Account")).Returns("/Account");

    controller.ControllerContext = new ControllerContext(httpContextBase.Object, new RouteData(), controller);

    controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, new RouteData()), routes);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文