Fluent MVC Route Testing Helper
- by Nettuce
static class GetUrlFromController<T> where T : Controller
{
public static string WithAction(Expression<Func<T, ActionResult>> expression)
{
var controllerName = typeof(T).Name.Replace("Controller", string.Empty);
var methodCall = (MethodCallExpression)expression.Body;
var actionName = methodCall.Method.Name;
var routeValueDictionary = new RouteValueDictionary();
for (var i = 0; i < methodCall.Arguments.Count; i++)
{
routeValueDictionary.Add(methodCall.Method.GetParameters()[i].Name, methodCall.Arguments[i]);
}
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
return UrlHelper.GenerateUrl(null, actionName, controllerName, routeValueDictionary, routes, ContextMocks.RequestContext, true);
}
}
I'm using FluentAssertions too, so you get this:
GetUrlFromController<HomeController>.WithAction(x => x.Edit(1)).Should().Be("/Home/Edit/1");