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:

    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home",
          action = "Index",
          id = UrlParameter.Optional }

The example test is:

public void DefaultRouteTest()
    var routes = new RouteCollection();
    var application = new Application();

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

    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.

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: