Testing Routes in ASP.NET MVC

Testing your routes in an ASP.NET MVC application is essential. However, most people tend to do this by testing the routes themselves. I like to take a slightly different approach here: I like to set expectations as how I would like my controller actions to be invoked; In other words, what their URL should look like. I also want to test this behavior both ways: inbound and outbound, when invoking an action and when generating a link.

I've put together a little base class that helps a lot for avoiding boilerplate code in when testing routes with that philosophy in mind. Here's what the end result looks like:

public class CustomerControllerRouteTests : RouteTestsBase<CustomerController>
    public void Edit()
        AssertRoute(x => x.Edit(1));

Under the covers, it does the following:

  • Sets up stubs and register routes for the main application as well as for every areas
  • It tests that the URL "~/Customer/Edit/1" invokes the action Edit(1) on the CustomerController class
  • It also tests that Url.Action(MVC.Customer.Edit(1)) (using T4MVC) will generate the link "~/Customer/Edit/1".

For now, the code is very basic and it doesn't provide nice support for things like ambient route values and additional route data, but it's a pretty good start.

However, the base class does provide support for ignoring arguments in actions. For instance, the following won't validate that the id parameter was properly mapped by our route:

AssertRoute(x => x.Edit(Ignore<int>()));

This Ignore method comes in quite handy, because Expressions (the type of the argument provided to the AssertRoute method) don't support method calls with default values in them (and most of us use them quite often in controller actions.)

You can find a link to the Gist for the base class here. Keep in mind that this is only a draft and also a work in progress. I may update this along with a future blog post. As always, feel free to copy-paste the code, no strings attached. And don't hesitate to fork it on GitHub.

Now, there is absolutely no excuse for not testing your routes. Just do it already!

Posted by: Bryan Menard
Last revised: 04 Mar, 2013 08:53 AM History


No comments yet. Be the first!

No new comments are allowed on this post.