In this tip, I demonstrate how you can create unit tests for the routes in your ASP.NET MVC applications. I show how to test whether a URL is being mapped to the right controller, controller action, and action parameters.
If you are being virtuous about test-driven development when building an ASP.NET MVC application, then you should write unit tests for everything. Write the unit test first then write the code that satisfies the test. Repeat, repeat, repeat, ad nauseam.
Routes are a very important part of an MVC application. A route determines how a URL is mapped to a particular controller and controller action. Since routes are such an important part of an MVC application, you need to write unit tests for your routes. In this tip, I show you how to write unit tests for routes by faking the HTTP Context.
Creating a Route Table
You create the routes for an MVC application in the Global.asax file. In other words, they are defined in the GlobalApplication class. The default Global.asax file is contained in Listing 1.
Listing 1 -- Global.asax (VB.NET)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace DefaultOne
{
public class GlobalApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
Listing 1 -- Global.asax (C#)