Home > ASP.NET MVC, dotnet 4 > Mocking Routes

Mocking Routes

I have a done a couple of post on how good TDD is and the use of Moq framework and today I am sharing some code to put all these ideas into practice with a real life project.

I have been working in ASP.NET MVC for sometime and this is one area where I first started using Moq and TDD i.e. testing ASP.NET MVC routes. This unit test project is part of the SparkViewEngine post i did some time ago and goes on to show good the MVC architecture is.

The first and foremost thing is to follow the triple “A” principle for writing unit test i.e.

  • Arrange
  • Act
  • Assert

Lets write some code to Mock the HttpContextBase in order to simulate an Http web request and then we are going to test our routes to verify that it maps to our controllers properly.

Mocking the HttpContextBase

As part of the “Arrange” we will create a RouteCollection object and pass it to RegisterRoutes method of the application class. This is the class which inherits from HttpApplication class and gets created in your Global.asax.cs file when you create a new MVC application.


In the next test we will test that our routes for a detail view. This is where the whole principle of “Separation of Concerns” really shines, we are able to test our routes with hosting on web server, without creating any web page or server pages etc.

Testing Person details

If you notice carefully you can see how I have named these test and have a lot of resemblence with Behaviour Driven Development (BDD) as I am a huge fan of BDD too.

Test View

If your arrange your test view as shown above you will see the highlighted line is really good in terms of readability. Just follow the pattern like

     For {Namespace} when {Class Name} the result expected is {Test Name}

You will see it reads like “For SparkViewEngineTest when TestingRoutes the result expected is This_goes_to_Person_Index_action” .

The whole sentence makes a lot of sense and is quite helpful when working on large projects with lots of unit test. (Another nice pattern to follow for your projects)

And when we run our unit tests we can verify our results.

  1. Yogesh
    August 25, 2010 at 1:24 am

    Good post Prashant. I appreciate BDD but I don’t like any pattern that forces me to_use_underscores. I just can’t imagine writing or reading code with too many underscores.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: