Thursday, 31 May 2012

Unit testing MVC routes

If you are using the MVC Routing engine, you can test your routes to ensure that they work as expected.

To test the default route:

[Test]
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home",
          action = "Index",
          id = UrlParameter.Optional }
);

The example test is:

[Test]
public void DefaultRouteTest()
{
    var routes = new RouteCollection();
    var application = new Application();
    application.RegisterRoutes(routes);

    var context = new Mock<httpcontextbase>();
    context.Setup(p => p.Request.AppRelativeCurrentExecutionFilePath)
                                   .Returns("~/");
    var routeData = routes.GetRouteData(context.Object);

    Assert.AreEqual(((Route)routeData.Route).Url, 
                    "{controller}/{action}/{id}");
    Assert.AreEqual("Home", routeData.Values["controller"]);
    Assert.AreEqual("Index", routeData.Values["action"]);
}

This came from an original post by Scott Gu, that we had to change slightly. http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

The original code was causing the first parameter to drop the first character. i.e. For the default route, the controller was return 'ome' instead of 'home'.

No comments: