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>
4: [Test]
5: public void SetHttpMethodTest()
6: {
7: var mockContext = HttpContextBaseMock.New();
8:
9: mockContext.Request.SetHttpMethod("BYAH");
10:
11: Assert.AreEqual("BYAH", mockContext.Request.HttpMethod);
12: }
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.