Categories
Posts

MVC Route Testing Boilerplate with JustMock

Back in the day, Phil Haack wrote up a good guide for unit testing the routes created in ASP.NET MVC. I just set up these tests in a new MVC 4 project with JustMock as my mocking framework, so I wanted to put up my small modifications of his code to work there.

First we have a few helper methods that mock up an HttpContextBase and allow the routes to be rendered into RouteData.

[code language=”csharp”]
public static void AssertRoute(RouteCollection routes, string url,
Dictionary<string, string> expectations)
{
var httpContextMock = Mock.Create<HttpContextBase>();
Mock.Arrange(() => httpContextMock.Request.AppRelativeCurrentExecutionFilePath)
.Returns(url);

RouteData routeData = routes.GetRouteData(httpContextMock);
Assert.IsNotNull(routeData, "Should have found the route");

foreach (string property in expectations.Keys)
{
Assert.IsTrue(string.Equals(expectations[property],
routeData.Values[property].ToString(),
StringComparison.OrdinalIgnoreCase)
, string.Format("Expected ‘{0}’, not ‘{1}’ for ‘{2}’.",
expectations[property], routeData.Values[property].ToString(), property));
}
}

public static void AssertIgnoreRoute(RouteCollection routes, string url)
{
var httpContextMock = Mock.Create<HttpContextBase>();
Mock.Arrange(() => httpContextMock.Request.AppRelativeCurrentExecutionFilePath)
.Returns(url);

RouteData routeData = routes.GetRouteData(httpContextMock);
Assert.IsNotNull(routeData, "Should have found the route");
Assert.IsInstanceOf<StopRoutingHandler>(routeData.RouteHandler);
}
[/code]

Dests for the default route and the basic controller/action route.
[code language=”csharp”]
[Test]
public void RegisterRoutes_AddsDefaultRoute()
{
var collection = new RouteCollection();
RouteConfig.RegisterRoutes(collection);
var expectations = new Dictionary<string, string>();
expectations.Add("controller", "home");
expectations.Add("action", "index");
expectations.Add("id", "");
AssertRoute(collection, "~/", expectations);
}

[Test]
public void RegisterRoutes_AddsControllerActionIdRoute()
{
var collection = new RouteCollection();
RouteConfig.RegisterRoutes(collection);
var expectations = new Dictionary<string, string>();
expectations.Add("controller", "home");
expectations.Add("action", "index");
expectations.Add("id", "1");
AssertRoute(collection, "~/Home/Index/1", expectations);
}
[/code]

…and an easy test to make sure that axd handlers are not routed with the routing engine.
[code language=”csharp”]
[Test]
public void RegisterRoutes_IgnoresAxd()
{
var collection = new RouteCollection();
RouteConfig.RegisterRoutes(collection);
AssertIgnoreRoute(collection, "handler.axd/somestuffhere");
}
[/code]