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.


New Year Promises

Everything is late. Even my new year promises are late – it’s nearly February after all. My excuse is that I’ve been Down Under since new years day. It was an awesome trip but I returned with some pretty heavy jet lag. I’ve never felt such debilitating exhaustion before.

So, now for my new years promises. I realise that I’ve been seriously neglecting this blog, but this year I will be a lot more active on it. I also have a new version of this site that I began working on last year that I will finish and get up quite soon.