ASP.Net MVC 2: mocking your HTTP layer

By: on February 21, 2011

We recently started a project using Microsoft’s ASP.NET MVC 2 framework. Since I’m pretty big on test driven development, I immediately wanted to start unit testing the controllers. It turns out that it’s a bit harder than I thought: in production, MVC does a whole bunch of stuff before execution ever reaches your controllers. And if you naively just start applying TDD, you get all sorts of funky NullReferenceExceptions deep in the bowels of MVC.

Well, Google is our friend, as always, and very soon I was reading Craig Stuntz’s answer on StackOverflow. I had to tweak things a bit. First, Moq‘s API changed a bit, and uses Setup() instead of Expects(). Second, MVC as part of its model binding looks in all sorts of places for values it might need to apply to your ViewModel objects. Through some trial and error, and reading the MVC source code, I came up with the following, which supplies a bunch of empty dictionaries for just about everywhere MVC looks for model binding data.

FacebookTwitterGoogle+

Comment

Post a comment

Your email address will not be published.

*

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