Asp.Net HttpSessionState in Microsoft Unit Tests Framework

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.

Comments

# re: Asp.Net HttpSessionState in Microsoft Unit Tests Framework
Gravatar Wow! That was exactly what i´ve been looking for a long time - works perfectly for me - thx!!
Left by Rudolf Stepan on 3/27/2010 12:21 AM
# re: Asp.Net HttpSessionState in Microsoft Unit Tests Framework
Gravatar Frames have always been a necessary support for the illusions inherent in perspectival art. Such systems require containment in order to help the viewer to believe the illusion of 3-D space, and for the illusion to have its proper effect.
Left by sito di casinò in rete on 4/6/2010 11:30 PM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 8 and 5 and type the answer here:

Preview Your Comment.