Posts

Showing posts from June, 2012

How to Mock an HttpContext for Unit Testing

I recently made some modifications to a class written by another programmer. When I went to write a unit test for my new additions, I found that the class made use of the statically accessible HttpContext.Current object. For my unit test, I wanted to be able to mock this out and use dependency injection to pass the mock in. Here are the steps I took to accomplish this. First, a brief summary of the classes I worked with to get this done: HttpContext: The original ASP.NET HttpContext. It has no base class and is not virtual, so it can't be mocked. HttpContextBase: Introduced in .NET 3.5 as a replacement to HttpContext. Abstract, and therefore mockable. This is the type to use as a parameter when injecting. HttpContextWrapper: Also introduced in .NET 3.5, it is an implementation of HttpContextBase. You can instantiate a new instance of this class from an HttpContext by passing the HttpContext into HttpContextWrapper's constructor (Example: new HttpContextWrapper(HttpContext