Saturday, August 23, 2008

[.NET] How to Simulate HttpContext Cookies

This might be useful if you're developing an ASP.NET application and you need to Unit Test (for example with NUnit or some other unit testing framework) some .NET component but you cannot do it because your classes use cookies.


using System.Web;
using System.IO;
using System.Web.Hosting;
//...
//...
//...
//Initialize this stuff with some crap
string appVirtualDir = "/";
string appPhysicalDir = @"C:\Documents and Settings\";
string page = @"localhost";
string query = string.Empty;
TextWriter output = null;
//Create a SimpleWorkerRequest object passing down the crap
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
//Create your fake HttpContext instance
HttpContext.Current = new HttpContext(workerRequest);
//Create your fake cookie
HttpCookie myCookie = new HttpCookie("myTestCookie", "value");
HttpContext.Current.Request.Cookies.Add(myCookie);
//...
//... somewhere else in your code
//...
//create a cookie object
HttpCookie anotherCookie;
//Get your cookie from the HttpContext
anotherCookie = HttpContext.Current.Request.Cookies.Get(0);
string cookieName = anotherCookie.Name;//cookieName should be now "myTestCookie"
string cookieValue = anotherCookie.Value;//cookieValue should be now "value"


You can use the same strategy to stuff the HttpContext with whatever you may need - maybe your problem are not cookies but some other HttpContext property your classes use.

Anyway I didn't figure this out all by myself - most of the inspiration came from this post on Haacked: Simulating HttpContext (btw - he says he has a better version of the post in the first line but for what I needed it I do not agree).

kick it on DotNetKicks.com

1 comment:

Clarence Klopfstein said...

Awesome! Thanks, your code was a lot easier to implement than other bits I've seen online.