How can I generate the URLs corresponding to the controller, action, and parameters (for a given ASP.NET MVC project) in another project (a class library used for testing)?
如何在另一个项目(用于测试的类库)中生成与控制器,操作和参数(对于给定的ASP.NET MVC项目)相对应的URL?
All I have found so far is HtmlHelper.GenerateRouteLink, but didn't find yet how to pass the correct request context and route collection.
到目前为止我找到的只是HtmlHelper.GenerateRouteLink,但是还没有找到如何传递正确的请求上下文和路由集合。
1 个解决方案
#1
Try this:
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var context = new Mock<HttpContextBase>();
var urlHelper = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
var url = urlHelper.Action("action", "controller", new { id = ... });
From SO - ASP.NET MVC: Unit testing controllers that use UrlHelper
从SO - ASP.NET MVC:使用UrlHelper的单元测试控制器
#1
Try this:
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var context = new Mock<HttpContextBase>();
var urlHelper = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
var url = urlHelper.Action("action", "controller", new { id = ... });
From SO - ASP.NET MVC: Unit testing controllers that use UrlHelper
从SO - ASP.NET MVC:使用UrlHelper的单元测试控制器