Total Pageviews

Wednesday, October 10, 2012

Unit testing code that uses HttpContext.Current.Session


Use can simply use this class to set up a fake one :)

private static void SetFakeHttpContext()
{
    var httpRequest = new HttpRequest("", "http://yoursite/", "");
    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);

    httpContext.Items["AspSession"] = typeof (HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] {typeof (HttpSessionStateContainer)},
                null)
                .Invoke(new object[] {sessionContainer});

    HttpContext.Current = httpContext;
}

No comments:

Post a Comment