ASP.NET MVC:模拟controller.Url.Action [英] ASP.NET MVC: Mock controller.Url.Action

查看:159
本文介绍了ASP.NET MVC:模拟controller.Url.Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网址在我的ASP.NET MVC应用程序菜单从控制器/动作产生。因此,他们呼吁

Urls for menus in my ASP.NET MVC apps are generated from controller/actions. So, they call

controller.Url.Action(action, controller)

现在,我怎么做单元测试这项工作?
我用MVCContrib成功地与

Now, how do I make this work in unit tests? I use MVCContrib successfully with

var controller = new TestControllerBuilder().CreateController<OrdersController>();

但无论我尝试用它做我得到controller.Url.Action(动作控制器)用的NullReferenceException失败,因为地址== NULL。

but whatever I try to do with it I get controller.Url.Action(action, controller) failing with NullReferenceException because Url == null.

更新:它不是关于如何拦截HttpContext的。我做这几种方式,使用MVCContrib,伪造的斯科特Hanselman的例子,也是一个来自<一个href=\"http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx\">http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx.这并不能帮助我,因为我需要知道什么值伪造...是ApplicationPath?我该如何设置?是否需要符合所谓的控制器/行动?也就是说,怎么办Url.Action工作以及如何满足呢?

Update: it's not about how to intercept HttpContext. I did this in several ways, using MVCContrib, Scott Hanselman's example of faking, and also the one from http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx. This doesn't help me because I need to know WHAT values to fake... is it ApplicationPath? How do I set it up? Does it need to match the called controller/action? That is, how do Url.Action works and how do I satisfy it?

另外,我知道我可以做IUrlActionAbstraction并用它去......但我不知道我想这样做。毕竟,我有MVCContrib /模拟全功率和为什么需要另一个抽象。

Also, I know I can do IUrlActionAbstraction and go with it... but I'm not sure I want to do this. After all, I have MVCContrib/Mock full power and why do I need another abstraction.

推荐答案

下面是你可以如何使用MvcContrib的TestControllerBuilder嘲笑UrlHelper:

Here's how you could mock UrlHelper using MvcContrib's TestControllerBuilder:

var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
HomeController controller = CreateController<HomeController>();

controller.HttpContext.Response
    .Stub(x => x.ApplyAppPathModifier("/Home/About"))
    .Return("/Home/About");

controller.Url = new UrlHelper(
    new RequestContext(
        controller.HttpContext, new RouteData()
    ), 
    routes
);
var url = controller.Url.Action("About", "Home");
Assert.IsFalse(string.IsNullOrEmpty(url));

这篇关于ASP.NET MVC:模拟controller.Url.Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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