Fluent MVC Route Testing Helper

Posted by Nettuce on Geeks with Blogs See other posts from Geeks with Blogs or by Nettuce
Published on Tue, 15 Feb 2011 21:12:49 GMT Indexed on 2011/02/15 23:26 UTC
Read the original article Hit count: 165

Filed under:
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");

 

© Geeks with Blogs or respective owner