Tuesday, 4 November 2008

Faking HTTPContext in Unit Tests

You may often come across some area of your application where you need to test using the HTTPContext values.  Thing is that HTTPContext doesn’t exist in a test application and you probably don’t want to mess around with HostType() variables or trying to create a “real” context in code.  So here’s a snippet that will create a simple worker request context for your application to test with

TextWriter tw = new StringWriter();
HttpWorkerRequest wr = new SimpleWorkerRequest("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", tw);
HttpContext.Current = new HttpContext(wr);

I can’t take credit for it, I found it here on Jeff’s Junk (good on ya Jeff!).  Once you have put your HttpContext in place you can setup whatever information you need for your unit test.  In my case I wanted to test a user called “usernotfound” so my unit test starts off like so;

// Setup the user account for testing.
IIdentity identify = new System.Security.Principal.GenericIdentity("usernotfound");
IPrincipal currentUser = new System.Security.Principal.GenericPrincipal(identify, null);
 
TextWriter tw = new StringWriter();
HttpWorkerRequest wr = new SimpleWorkerRequest("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", tw);
HttpContext.Current = new HttpContext(wr);
 
System.Web.HttpContext.Current.User = currentUser;

And away I go….

No comments: