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.