technology from back to front

ASP.Net MVC 2: mocking your HTTP layer

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.

Frank Shearar
  1. [...] to Vote[FriendFeed] ASP.Net MVC 2: mocking your HTTP layer « LShift Ltd. (4/21/2011)Thursday, April 21, 2011 from   Last >>   Advertise [...]


five × = 30

2000-14 LShift Ltd, 1st Floor, Hoxton Point, 6 Rufus Street, London, N1 6PE, UK+44 (0)20 7729 7060   Contact us