在对 ASP.NET MVC 路由进行单元测试时,我能否发现哪个命名路由与 URL 匹配?
我正在使用 nUnit 来测试 MVC2 项目的路由。
当我在 Global.asax.cs 中注册路由时,我为每个路由指定一个唯一的名称并指定其 RouteData,例如:
routes.MapRoute(
"ShowRecord",
"{controller}/{id}",
new { action = "Show" },
new { id = @"^\d+$" }
);
在我的单元测试中,我然后在 RouteCollection 对象上调用 RegisterRoutes,并根据我想要的每个 url 检查生成的 RouteValueDictionary进行测试。我为此使用了一个模拟的 HttpContext,一切正常。
然而,我真正想知道的是,哪个命名路由与提供的 URL 匹配?当我的单元测试获得了被测URL对应的RouteData对象后,我能具体发现匹配的是哪条路由吗?是通过名称(例如上例中的“ShowRecord”)还是通过其在 RouteCollection 对象中的索引?
I'm using nUnit to test the routing of my MVC2 project.
When I register my routes in Global.asax.cs, I give each route a unique name and specify its RouteData, eg:
routes.MapRoute(
"ShowRecord",
"{controller}/{id}",
new { action = "Show" },
new { id = @"^\d+$" }
);
In my unit tests I then invoke RegisterRoutes on a RouteCollection object, and inspect the resulting RouteValueDictionary against each url that I want to test. I use a mocked HttpContext for this, and everything works fine.
However, what I'd really like to know is, which named route(s) matched the supplied URL? Once my unit test has obtained the RouteData object corresponding to the URL under test, can I discover specifically which route was matched? Either by name (eg "ShowRecord" in the example above), or by its index in the RouteCollection object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,你不能这样做。请参阅如何从 RouteData 获取路线名称?了解更多信息语境。
您可以做的是将路由名称添加到路由的 DataTokens 字典中。 DataToken 用于以某种对您和您的应用程序重要的方式标记路线。它们不会影响路由匹配和 url 生成。
路由名称的作用是为路由引擎提供查找路由的查找键。它的作用很像 SQL Server 中的索引。
Unfortunately, you cannot do this. See How do I get Route name from RouteData? for more context.
What you could do is add the route name to the route's DataTokens dictionary. DataTokens are used to mark a route in some way that's significant to you and your application. They don't affect anything with regarding to route matching and url generation.
The purpose of the route name is to provide a lookup key to the routing engine for looking up routes. It acts much like an index in SQL Server.