First you'll have to initialize HttpContext.Current
:
HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", "") {},
new HttpResponse(new StringWriter()));
Then you'll have to set the session:(Necroskillz has explained the way to do this in his blog)
public static void SetFakeSession(this HttpContext httpContext)
{
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 });
}
The following snippet shows how it works:
[TestMethod]
public void TestMethod1()
{
HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", "") {},
new HttpResponse(new StringWriter()));
HttpContext.Current.SetFakeSession();
HttpContext.Current.Session["foo"] = 1;
Assert.AreEqual(1, HttpContext.Current.Session["foo"]);
}