MVC 3, Technical, Unit Testing

Mocking HttpContext (And setting it’s session values)

Thanks to this Stack Overflow answer that pushed me in the right direction, I was able to mock HttpContext and set values that it encompasses.

Firstly, you will need a helper somewhere in your test project that will return you a mock HttpContext:

public static class MockHelpers
  public static HttpContext FakeHttpContext()
    var httpRequest = new HttpRequest("", "http://localhost/", "");
    var stringWriter = new StringWriter();
    var httpResponce = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponce);

    var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false);

    SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

    return httpContext;

You will then need to Add and Reference System.Web in your test project. Once done, you will be able to set your HttpContext and set HttpContext specific values, such as session variables. In the example below, I am setting up the HttpContext in the SetUp method of a unit test:

public void SetUp()
	HttpContext.Current = MockHelpers.FakeHttpContext();
	HttpContext.Current.Session["SomeSessionVariable"] = 123;

Another more heavy solution to the above would be to use a factory to get at and create your session. I opted for the solution above as it meant not changing my application code to fit in with my unit tests.

6 thoughts on “Mocking HttpContext (And setting it’s session values)

  1. Hi, do you know of a way to mock the HttpContext.Application? Looking in the decompiled System.Web it appears to be calling a Factory which is generating a new Application every time that property is referenced. Any ideas on getting around that?

Leave a Reply to Sheena Abraham Cancel reply

Your email address will not be published. Required fields are marked *