ASP.NET MVC:使用UrlHelper单元测试控制器 [英] ASP.NET MVC: Unit testing controllers that use UrlHelper

查看:97
本文介绍了ASP.NET MVC:使用UrlHelper单元测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个控制器的动作,一个是被称为在一个Ajax请求,则返回一个URL到客户端,以便它可以做一个重定向。我使用 Url.RouteUrl(..),并在我的单元测试失败,因为 Controller.Url 参数是不是pre-填写。

One of my controllers actions, one that is being called in an Ajax request, is returning an URL to the client side so it can do a redirection. I'm using Url.RouteUrl(..) and during my unit tests this fails since the Controller.Url parameter is not pre-filled.

我尝试了很多东西,其中包括试图存根 UrlHelper (这失败),手动创建一个 UrlHelper RequestContext的具有存根 HttpContextBase (它未能在 RouteCollection.GetUrlWithApplicationPath 调用)。

I tried a lot of things, among others attempting to stub UrlHelper (which failed), manually creating a UrlHelper with a RequestContext that has a stubbed HttpContextBase (which failed on a RouteCollection.GetUrlWithApplicationPath call).

我已经搜索谷歌,但发现关于这个问题几乎没有。我做使用 Url.RouteUrl 在我的控制器动作令人难以置信的东西愚蠢?是否有更简单的方法?

I have searched Google but found virtually nothing on the subject. Am I doing something incredibly stupid using Url.RouteUrl in my Controller action? Is there an easier way?

为了让事情变得更糟,我希望能在我的单元测试,以测试返回的URL - 其实我只知道它重定向到正确的路线感兴趣,但因为我返回一个网址而不是一个路线,我想控制解决的URL(例如,通过使用存根 RouteCollection ) - 但我会很乐意让我的测试传递给开始的时候。

To make it even worse, I'd like to be able to test the returned URL in my unit test - in fact I'm only interested in knowing it's redirecting to the right route, but since I'm returning an URL instead of a route, I would like to control the URL that is resolved (eg. by using a stubbed RouteCollection) - but I'll be happy to get my test passing to begin with.

推荐答案

下面是我的测试(+的xUnit MOQ)只是类似的情况下(控制器使用Url.RouteUrl)

Here is one of my tests (xUnit + Moq) just for similar case (using Url.RouteUrl in controller)

希望这有助于:

var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);

var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier("/post1")).Returns("http://localhost/post1");

var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);

var controller = new LinkbackController(dbF.Object);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

这篇关于ASP.NET MVC:使用UrlHelper单元测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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