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:

  
[SetUp]
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.

Advertisements

One comment


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s