Wednesday, 15 October 2008

How to use the HttpContext cache in a non-web (test) environment

Question:
How to test a class that relies on HttpContext.Current.Cache (or so) in order to work.
If you test this in NUnit, for example, there will be no current HttpContext around.
So abstract the access to the Context away and in the property you'll provide another cache if need is.



Answer:

/// 
/// Give me the current Httpcontext cache or if you do not have (in Nunit test) 
/// then get the httpRuntime cache. (it seems it is the same)
/// 
private static Cache MyCache
{
   get
   {
      return (HttpContext.Current == null) ? HttpRuntime.Cache : HttpContext.Current.Cache;
   }
}



But here is how HttpContext.Cache is implemented

public Cache Cache
{
get
{
return HttpRuntime.Cache;
}
}


So, calling HttpRuntime.Cache should be fine in all cases.

No comments: