Home > Asp.net > Testing Routing and URL Generation in ASP.NET MVC

Testing Routing and URL Generation in ASP.NET MVC

In ASP.NET MVC, getting your routes setup properly can be tricky if you have a lot of routes. Whenever something is tricky, and might be touched often, having a set of unit tests around it can very helpful to ensure you aren’t breaking it when you make changes. Lots of routes can definitely qualify; your users rely on unbroken links and stable URLs for a good experience.

The techniques shown here not only work for unit testing, but can also be used outside of the ASP.NET pipeline when you need to interact with the routing system (for example, to generate URLs from a service). The routing system used by ASP.NET MVC uses the abstraction classes, so the actual running ASP.NET pipline isn’t required.

Stubbing

The key to getting all this to work is the use of stub versions of the HTTP abstraction classes (namely, context, request, and response objects). The routing system uses very little of these actual classes, so the stubs are fairly simple. The easiest way to figure out what’s being used is to use a mock framework in strict mode and see which requests fail.

The end of this blog post contains the source to the stubs we’ll be using below. These stubs work for both incoming and outgoing routing tests.

Incoming Routes

Testing incoming routes means feeding a request URL into the routing system and looking at the route values that come back out the other side.

Our stubs will enable us to write tests like this:

 Outgoing Routes

Testing outgoing routes means using the UrlHelper class to create URLs, given a specific set of values. With the stubs provided, you could also use the UrlHelper class in a non-MVC project to generate URLs for you. All you need access to is the routes and the app path where the application is running.

Our stubs will enable us to write tests like this:

 The implementation of GetUrlHelper looks like this:

 Stub Source

This one set of stubs can be used for both incoming and outgoing route testing:

 

 

 

 

 

 

 

 

 

 

 

This Article is TAGGED in , , , , , . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">