Building on what Phil Haack wrote a while ago to test your mvc routing. It is important to test your routing as it controls exactly where the users will go when they make a request. Especially if you have to maintain a complex CMS framework.
Haack used the moq framework to write a test helper method, I have modified his code to use NSubstitue, a different mocking framework:
public static class RouteTestHelper
{
public static void AssertRoute(RouteCollection routes, string url, object expectations)
{
var httpContextMock = Substitute.For<httpcontextbase>();
httpContextMock.Request.AppRelativeCurrentExecutionFilePath.Returns(url);
RouteData routeData = routes.GetRouteData(httpContextMock);
Assert.IsNotNull(routeData, "Should have found the route");
foreach (var kvp in new RouteValueDictionary(expectations))
{
Assert.IsTrue(string.Equals(kvp.Value.ToString(), routeData.Values[kvp.Key].ToString(), StringComparison.OrdinalIgnoreCase)
, string.Format("Expected '{0}', not '{1}' for '{2}'.", kvp.Value, routeData.Values[kvp.Key], kvp.Key));
}
}
}
This will build the routes table in your MVC application and we mock the request via HttpContextBase. The expectations
should contain the key/value pairs you expect to be in the routeData.Values
.
Below is an example unit test.
[TestMethod]
public void CategoryRoute()
{
var routes = new RouteCollection();
CnMvcApplication.RegisterRoutes(routes);
RouteTestHelper.AssertRoute(routes, "~/news", new { controller = "category", action = "index"});
}
Hopefully this is easy to understand and helps you setup your unit tests quickly.