Incandescent Blur

August 28, 2009

Unit Testing with Cache

Filed under: Code Testing — admin @ 12:36 pm

One time I was working on a TEST-project for one of my web projects, I basically needed to test a UserControl. However, one of the function I need to test is referring to the HttpContext.Current.Cache. .

Running the test without a running web application will cause an error because HttpContext.Current.Cache is null.

So the solution was to create a sort of a dummy HttpContext.Current.

and heres how to do it.



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


after this HttpContext.Current.Cache is now accessible.

or even simpler



HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));


However if you want to access HttpContext.Current.Session
then I suggest you check this Website for more options
Unit Test Web Code

You can also download the code files for simulating HTTP stuff. It Should be easy to find in the link above.

Powered by WordPress