title: Unit test HttpContext.Current.Cache or other server-side methods in C#?
body: <p>When creating a unit test for a class that uses the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx" rel="nofollow noreferrer"><code>HttpContext.Current.Cache</code> class</a>, I get an error when using NUnit.  The functionality is basic - check if an item is in the cache, and if not, create it and put it in:</p>
  
  <pre><code>if (HttpContext.Current.Cache["Some_Key"] == null) {
      myObject = new Object();
      HttpContext.Current.Cache.Insert("Some_Key", myObject);
  }
  else {
      myObject = HttpContext.Current.Cache.Get("Some_Key");
  }
  </code></pre>
  
  <p>When calling this from a unit test, it fails with at <code>NullReferenceException</code> when encountering the first <code>Cache</code> line.  In Java, I would use <a href="http://jakarta.apache.org/cactus/index.html" rel="nofollow noreferrer">Cactus</a> to test server-side code.  Is there a similar tool I can use for C# code?  <a href="https://stackoverflow.com/questions/244280/creating-a-system-web-cachcing-cache-object-in-a-unit-test">This SO question</a> mentions mock frameworks - is this the only way I can test these methods?  Is there a similar tool to run tests for C#?</p>
  
  <p>Also, I don't check if the <code>Cache</code> is null as I don't want to write code specifically for the unit test and assume it will always be valid when running on a server.  Is this valid, or should I add null checks around the cache?</p>