We have some unit tests that tests code which relies on a variable stored in the Asp.Net session state (HttpSessionState) accessed from the HttpContext.Current.Session property.
Our unit tests run within the Microsoft Unit Test framework that comes with Visual Studio, but I think that the technique should apply to other frameworks such as NUnit.
Without doing any work HttpContext.Current returns null. It appears quite easy to make set a current HttpContext to contain a session:
HttpContext.Current = new HttpContext(new HttpRequest("", "http://localhost/", ""), new HttpResponse(new System.IO.StringWriter()));
Now HttpContext.Current returns a context, but HttpContext.Current.Session still returns null. You can attach a basic session object with the following line:
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
HttpContext.Current, new HttpSessionStateContainer("",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 20000, true,
HttpCookieMode.UseCookies, SessionStateMode.Off, false));
Now HttpContext.Current.Session can be assigned to and read from allowing my unit tests to run.
I think the code is best put in the a method marked with a [TestInitialize] attribute. The context should also be cleared when a test has completed:
[TestCleanup]
public void Clean()
{
HttpContext.Current = null;
}
I'm not expecting the HttpContext to work well for any other calls, but it might allow more than just interaction with the session.