I have been doing some Test-After Development unit testing on an ASP.NET MVC app and hit code that uses the cache through HttpContext.Current.Cache (I bet @serialseb would just love that!
) which as you may know is a royal pain in the arse for getting at or mocking without a web server.
As most sane people do I binged (that just does not sound right!) for an answer to my problem and came across a few interesting things but the closest I came initially was a post from Phil Haacked on his HttpSimulator cache where someone mentioned that using HttpRuntime got around the issue. I tired, it failed and I went back to Bing and came up with a post on Scott Hanselman’s blog where he details a conversation about simply including System.Web along with System.Web.Caching in non-web applications. I was skeptical but people have noted success with this method so I tried it and what did I find, it sodding well worked!
Granted the articles I found are old but this is the first time I have tried to unit test the Cache before so this was quite useful.
In other news I have ordered a copy of Working Effectively with Legacy Code by Michael Feathers from Amazon after @chriscanal recommended it, looking forward to having a read.



Andy,
First, read the book, it’s one of the must-read ones. And it’s by Michael Feathers, by the way.
Also, you can use Typemock Isolator for mocking HttpContext.
Cheers,
Gil
@Gil Zilberfeld I have been chewing through it and so far I am really quite impressed. I can see it being very useful in my current job.
Thanks for the catch on the author, I noticed that when I was reading it and head-desked but forgot to update the post.
Haven’t looked at Typemock yet but that is good to know. HttpContext is one of my many ASP.NET bugbears and having to test around it is such a pest, it is good to know there are ways.
Andy,
When you get to it (and you really should, if you want to do unit testing easily) let me know. I can answer any questions you might have.
But really, evaluate it and see if (how, really) it fits into your process. Especially in MVC you’ll start writing less code in order to write the tests.
Cheers,
Gil