Unit Testing MVC Area Route Mapping to Controller and Url Creation<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Unit Testing MVC Area Route Mapping to Controller and Url Creation

Posted on: April 21, 2015

One of the key element of your website should be that every Url that you have should goes to the controller's action that you expect. This is also true when you are using an Asp.Net Html Helper that generate an URL. To be sure that you can rely that an Url links to the right action and that every Url generated have the right string structure, you must unit test them. This is far more important when your project start to become bigger and bigger. Routing rules can override a previous route and create unreachable code from your web interface. To solve that issue, every routes should be unit tested.

UnitTestControllerRouting 400x262

Asp.Net MVC routing system is quite interesting and easy to unit tests. I read that it is hard to unit test but this is not my experience. In this article, I will show you how to unit test routing from a specific AreaRegistration file. This is exactly the same process if you have your route inside the RouteConfig.cs file. Instead of using the area class, you use the RouteConfig class. They both use the System.Web.Routing.RouteTable and this is what we need to setup tests.

So before going into the detail, here is an example to unit test and Url to a controller's action.

2public void GivenRouteForContest_WhenPortefolioId() {
3 // Arrange
4 string url = Constants.Areas.CONTEST + "/1/Portefolio/2";
6 // Act
7 RouteData routeData = base.GetRouteDataForUrl(url).RouteData;
9 // Assert
10 Assert.IsNotNull(routeData);
11 Assert.AreEqual("Portefolio", routeData.Values[Constants.RoutePortionName.CONTROLLER]);
12 Assert.AreEqual("IndexById", routeData.Values[Constants.RoutePortionName.ACTION]);
13 Assert.AreEqual("1", routeData.Values[Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID]);
14 Assert.AreEqual("2", routeData.Values[Constants.RoutePortionName.ACTIVE_CURRENT_PORTEFEOLIO_ID]);

As you can see by this unit test example, the url is defined in the arrange section. The act part is a one liner that call a method that act as a proxy to call the real GetRouteData. To have access to that method, all my routing tests inherit from a testing class that allows me to call. I named that class RouteTestBase. It has a method is running between code which clear all routes and configures the route. This is where I have setup the configuration of the area I wanted to test. This is where you may want to use the global route configuration. This class has two public methods. The first one is used for unit testing string url to route data and the second one is to test Html Url helper to generate the string url.

1public class RouteTestBase {
2 [TestInitialize]
3 public void BetweenTest() {
4 RouteTable.Routes.Clear();
5 var areaRegistration = new ContestAreaRegistration();
6 var areaRegistrationContext = new AreaRegistrationContext(areaRegistration.AreaName, RouteTable.Routes);
7 areaRegistration.RegisterArea(areaRegistrationContext);
8 }
10 /// <summary>
11 /// From URL to Controller/Action, this method return the route and http context after passing the URL
12 /// into the RouteTable.
13 /// </summary>
14 /// <param name="url"></param>
15 /// <returns></returns>
16 protected RouteAndContext GetRouteDataForUrl(string url) {
17 var context = FakeHttpContext(requestUrl: "~/" + url);
18 RouteData routeData = RouteTable.Routes.GetRouteData(context);
19 return new RouteAndContext(context, routeData);
20 }
22 /// <summary>
23 /// Generate an UrlHelper to be used to generate URL string.
24 /// </summary>
25 /// <param name="appPath">Define the application path. By default, if all routing start from the domain than this should not be set.</param>
26 /// <returns>Html</returns>
27 protected UrlHelper GetUrlHelper(string appPath = "~/") {
28 HttpContextBase httpContext = FakeHttpContext(appPath:"/",requestUrl: appPath);
29 var routeData = RouteTable.Routes.GetRouteData(httpContext) ?? new RouteData();
30 RequestContext requestContext = new RequestContext(httpContext, routeData);
31 UrlHelper helper = new UrlHelper(requestContext, RouteTable.Routes);
32 return helper;
33 }
35 private HttpContextBase FakeHttpContext(string appPath="~/", string requestUrl = "/") {
36 // Mocks
37 var context = new Mock<HttpContextBase>();
38 var request = new Mock<HttpRequestBase>();
39 var response = new Mock<HttpResponseBase>();
40 var session = new Mock<HttpSessionStateBase>();
41 var server = new Mock<HttpServerUtilityBase>();
42 var user = new Mock<IPrincipal>();
43 var identity = new Mock<IIdentity>();
45 // Query String Parameters
46 var routePart = requestUrl;
47 var queryStringPart = requestUrl;
49 if (routePart.Contains("?")) {
50 var indexQueryString = routePart.IndexOf("?", StringComparison.InvariantCulture);
51 routePart = requestUrl.Substring(0, indexQueryString);
52 queryStringPart = requestUrl.Substring(indexQueryString + 1, requestUrl.Length - indexQueryString-1);
53 NameValueCollection parameters = new NameValueCollection();
54 var parametersList = queryStringPart.Split('&');
55 foreach (var paramter in parametersList) { var keyAndvalue = paramter.Split('='); parameters.Add(keyAndvalue[0], keyAndvalue[1]); }
56 request.Setup(req => req.Params).Returns(parameters);
57 }
59 // Setup all Http Context
60 request.Setup(req => req.ApplicationPath).Returns(appPath);
61 request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns(routePart);
62 request.Setup(req => req.PathInfo).Returns(string.Empty);
63 request.Setup(req => req.ServerVariables).Returns(new NameValueCollection());
64 response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>())).Returns((string virtualPath) => virtualPath);
65 user.Setup(usr => usr.Identity).Returns(identity.Object);
66 identity.Setup(ident => ident.IsAuthenticated).Returns(true);
67 context.Setup(ctx => ctx.Request).Returns(request.Object);
68 context.Setup(ctx => ctx.Response).Returns(response.Object);
69 context.Setup(ctx => ctx.Session).Returns(session.Object);
70 context.Setup(ctx => ctx.Server).Returns(server.Object);
71 context.Setup(ctx => ctx.User).Returns(user.Object);
73 return context.Object;
76 /// <summary>
77 /// Class used to return the RouteData and the HttpContextBase
78 /// </summary>
79 public class RouteAndContext {
80 public RouteAndContext(HttpContextBase httpContextBase, RouteData routeData) {
81 this.HttpContext = httpContextBase; this.RouteData = routeData;
82 }
84 public HttpContextBase HttpContext { get; private set; }
85 public RouteData RouteData { get; private set; }
86 }

Indeed this class has hard-coded area class in the TestInitialize method. But, my project contains only few areas and I want to keep everything simple. I will all every area one by one in this method. However, you could make it generic very easily by passing to the constructor of that method a list of AreaRegistrationContext.

The test concerning the Html's helper is also pretty simple once you have this class to inherit from. In you arrange you get the UrlHelper. You could set this initialization inside the method that run between each test, but this one allow to pass the application path. This parameter allows to not use the domain only has the base application path. The acting section of this unit test is the same as what is using when you are using the Html helper to generate an Url.

1[TestMethod] public void ControllerUserContest_ActionEnter() {
2 // Arrange
3 UrlHelper helper = base.GetUrlHelper(); var routeParameters = new RouteValueDictionary(new Dictionary<string, object>()) {
4 {Constants.AREA, Constants.Areas.CONTEST}, {Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID,1}
5 };
7 // Act
8 string url = helper.Action("Enter", "UserContest", routeParameters);
10 // Assert A
11 ssert.AreEqual("/" + Constants.Areas.CONTEST + "/1/Enter", url); }

The helper.Action calls the url helper Action method and this is why we are using this one to get the string Url to test.

1public virtual TagBuilder GenerateActionLink( [NotNull] string linkText, string actionName, string controllerName, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes) {
2 var url =_urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment);
3 return GenerateLink(linkText, url, htmlAttributes);

The code above is from Asp.Net MVC framework which shows what the GenerateActionLink is using the url helper Action method. So, as you can see, once you have the inherit base class, it is a matter of a single calls and some assertion to test all your routes. I strongly suggest that for each of your routes you have a single unit test to avoid any huge impact on your website.