Mocking System.Web.Caching.Cache - Layout or check for zero?

I am writing a few unit tests and wondering if it is beneficial to mock Cache , and if so, how?

Currently, in my tests, I mock the HttpContextBase and wrap it in a custom HttpContextFactory :

 var mockedHttpContextBase = new Mock<HttpContextBase>(); IHttpContextFactory httpContextFactory = new HttpContextFactory { Current = mockedHttpContextBase.Object }; 

and when my code consumes an IHttpContextFactory , I check if the cache is zero before doing anything with it.

 var cache = _httpContextFactory.Current.Cache; Func<SomeReturnType> doSomeWork = () => _foo.someMethodIExecute(param1,param2); return cache != null ? cache.GetOrStore("doSomeWorkCacheKey",doSomeWork, 900) : doSomeWork.Invoke(); 

Is it correct to check that the cache is zero, as it is every time I use it, or would you mock the cache also in the test so that it is not zero when performing unit tests?

+7
source share
2 answers

If your code assumes that the cache can be null and does checks before accessing it (as it is now), you need to have two unit tests for each cache access:

  • there is a cache and the element is saved and retrieved (check the GetOrStore call)
  • cache is null and you are simply claiming to call a delegate

If this is a common pattern (zero check), instead of two tests every time a cache dependency is required, I suggest wrapping it in a Null Object Pattern and checking it once and later, just use NOP as a dependency that can be mocked.

Edit : example mocking cache

 var cache = new Cache(); // Add takes more parameters; fill whatever is necessary to make it work cache.Add("doSomeWorkCacheKey", doSomeWork, ...); var mockedHttpContextBase = new Mock<HttpContextBase>(); // tell your mock to return pre-configured cache mockedHttpContextBase.Setup(m => m.Cache).Returns(cache); IHttpContextFactory httpContextFactory = new HttpContextFactory { Current = mockedHttpContextBase.Object }; 
+3
source

After a little searching, it seems that I can use HttpRuntime.Cache instead of System.Web.Caching.Cache when writing unit tests.

Thus:

var mockedHttpContextBase = new Mock<HttpContextBase>(); mockedHttpContextBase.Setup(m => m.Cache).Returns(HttpRuntime.Cache);

The cache should never be null (this would be a suitable exception if it were), so I can remove the null reference check from my code.

+13
source

All Articles