The way to do this is to avoid direct use of the HttpContext or other similar classes, and substitute them with mocks. After all, you’re not trying to test that the HttpContext functions properly (that’s microsoft’s job), you’re just trying to test that the methods got called when they should have.
Steps (In case you just want to know the technique without digging through loads of blogs):
-
Create an interface which describes the methods you want to use in your caching (probably things like GetItem, SetItem, ExpireItem). Call it ICache or whatever you like
-
Create a class which implements that interface, and passes methods through to the real HttpContext
-
Create a class which implements the same interface, and just acts like a mock cache. It can use a Dictionary or something if you care about saving objects
-
Change your original code so it doesn’t use the HttpContext at all, and instead only ever uses an ICache. The code will then need to get an instance of the ICache – you can either pass an instance in your classes constructor (this is all that dependency injection really is), or stick it in some global variable.
-
In your production app, set the ICache to be your real HttpContext-Backed-Cache, and in your unit tests, set the ICache to be the mock cache.
-
Profit!