Today whilst writing some tests utilising some legacy code (Legacy code is any code without tests!), I encountered a null reference exception as references to the HttpContext have made it into the business layer I was using. No IIS … No HttpContext … Thanks to Jason Bock and his wonderful article I will be back in business tomorrow!

I was sold after I added the following test to his tests. The cache object in particular was something I wanted to “mock”.


[TestMethod]
public void UseCache()
{
  HttpContext context = (new MockHttpContext(false)).Context;
  context.Cache.Add("test", "test value", null, DateTime.Now.AddMinutes(1),
    TimeSpan.Zero, CacheItemPriority.Normal,null);
  Assert.AreEqual(context.Cache.Get("test").ToString(), "test value");
  Assert.AreEqual(HttpContext.Current.Cache.Get("test").ToString(), "test value");
}

The article is well worth a (re-) read as it is a great “how-to” for using Reflector

Advertisements