ASP.NET MVC Unit Testing With HttpContextBase.Cache

9/6/2008 4:32:15 PM

Technologies

  • 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:

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

Jack

Jack

http://jack-fx.com
4/2/2009 2:57:11 AM

HttpRuntime.Cache is fine, while HttpContext.Cache not work in test project, but is there any difference?

Stéphan Parrot

Stéphan Parrot

http://www.exutoirerock.com
7/12/2010 8:20:15 AM

Thanks a lot! ;)

Ann

Ann

http://www.google.com
9/23/2010 3:26:52 AM

Thanks for information!

Paul Speranza

Paul Speranza

11/5/2010 1:35:59 PM

Thanks for this. You were the first search result in bing and my unit test worked on the first try!

Paul

This is the first time i’m visiting your site. I see lots of usefull stuffs in your site. Well done good job.

SEO Services India

SEO Services India

http://www.sonicinfosystem.com
1/25/2012 7:18:40 AM

I wonder how you got so good. This is really a fascinating blog, lots of stuff that I can get into. One thing I just want to say is that your Blog is so perfect!

Add Comment