ASP.NET MVC Unit Testing With HttpContextBase.Cache
9/6/2008 4:32:15 PMTechnologies
- ASP.NET MVC
- .NET Framework 3.5
I was trying to unit test a controller that made use of System.Web.Caching.Cache to store a chunk of data returned from the db that only needed to be fetched every 15 minutes or so. The test I was writing was to make sure that if the data was in the cache that it would be used instead of fetched. I thought this would be really straight forward:
- Instantiate System.Web.Caching.Cache
- Add my data to the cache
- Add the cache object to my HttpContextBase stub
- Set the stub on the controller
- Run the controller action
- Assert my returned data from the action
However, whenever I added items to the instantiated cache null reference exceptions would be thrown. After some reflector digging this is because the cache object is actually storing the data in an instance of System.Web.Caching.CacheInternal. ASP.net needs a thorough makeover . . .
After some googling I came across this great tip that showed how HttpRuntime.Cache properly instantiates CacheInternal. Problem solved.
1: Cache testCache = HttpRuntime.Cache;
Comments
HttpRuntime.Cache is fine, while HttpContext.Cache not work in test project, but is there any difference?
Thanks a lot! ;)
Thanks for information!
Paul Speranza
11/5/2010 1:35:59 PMThanks for this. You were the first search result in bing and my unit test worked on the first try!
Paul