I seldom need to deal with HttpContext and session directly in testing.
However if I ever need to fake the current HttpContext information, I use the following method (taken from here
private HttpContext CreateFakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://www.asp.net/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
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 });
return httpContext;
}
Then I set the current context
HttpContext.Current = CreateFakeHttpContext()
After I have fake context information, I can add session item like usual.