The ASP.NET MVC RC includes some significant improvements to
unit testing:
ControllerContext changed to no longer derive from
RequestContext
The RC build includes a refactoring of the ControllerContext
class that significantly simplifies common unit testing scenarios. The
ControllerContext class no longer derives from RequestContext and now instead
encapsulates RequestContext and exposes it as a property. The properties
of ControllerContext and its derived types are also now virtual instead of
sealed – making it significantly easier to create mock objects.
To see how this helps, let’s consider an action method like
below that uses both the “Request” and “User” intrinsic objects:
Figure 34
Testing the above action method with previous ASP.NET MVC
builds would have required mocking RequestContext and ControllerContext (with
some non-obvious constructors that also brought in a RouteData object).
With the RC build we can now unit test it like below (using Moq to mock a ControllerContext for
our Controller that allows us to simulate the Request.IsAuthenticated and
User.Identity.Name properties):
Figure 35
The refactoring improvements made help out not just with
testing Controller actions – but also help with testing filters, routes, custom
actionresult types, and a variety of other scenarios.