Testing/Mocking with the HttpContext

Developers sometimes use the Cache property in a HttpContext to store data across sessions. This is so that you don’t have pull static data from a data store over and over and just pull it once and store it in the HttpContext. If you do unit testing for your Controllers, then you’ll eventually run into a null value for the HttpContext property. Once you start messing with it, you’ll then notice the HttpContext property of your controller instance is read-only, so how the heck can you get that to not be null?!

To get around that you can use the following code to set it:

// you can set this in a helper method or set up method
HttpContext.Current = new HttpContext(
 new HttpRequest("", "http://tempuri.org", ""),
 new HttpResponse(new StringWriter())
 );

// initiate your controller with whatever mocked parameters you need for your controller
var controller = new YourController(someMoq.Object) {
  // set the ContollerContext property with the context from above
  ControllerContext = new ControllerContext {HttpContext = new HttpContextWrapper(HttpContext.Current)}
};

controller.HttpContext <= Not null anymore!

I pieced this together courtesy of the following links:

Share