4. August 2008 08:56
One of the advantages of the new ASP.NET MVC framework is improved testability. Testing simple controllers is as simple as testing any other class. Once you start accessing HttpContext-related things though (such as the request, response, etc), things become much more tricky. There's a few things in MVC Contrib that can help, but I've found them to be very lacking. For example, I was trying to test a controller that inspected the HttpMethod property of the request, but MVC Contrib provides no way to alter this value (at least not that I have found).
Instead, I found some extensions created by Alan Dean in the AltNetUK project on Google Code. These extension methods utilize Moq and enable you to do some really cool things, such as modify HttpContext properties:
1: /// <summary>
2: /// Verifies that the method correctly modifies the HttpMethod property.
3: /// </summary>
5: public void SetHttpMethodTest()
7: var mockContext = HttpContextBaseMock.New();
11: Assert.AreEqual("BYAH", mockContext.Request.HttpMethod);
We're still trying to figure out how to mock out a few more advanced things, like the user context. It is starting to look like it isn't doable easily, but I'll post an update if/when we manage to crack this scenario.
About Matt Honeycutt...
Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications.
He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.
He's also an author for Pluralsight,
where he publishes courses on everything from web applications to testing!