I’m writing some unit test and am wondering whether it’s advantageous to mock the Cache and if so, how?
Currently in my tests I’m mocking out the HttpContextBase and wrapping 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 null 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 right to check for the cache being null like this each time I use it or would you mock the cache also in the test so that it’s not null when running your unit tests?
If your code assumes cache can be
nulland performs checks before accessing it (as it does now), you need to have two unit tests for each cache access:GetOrStorecall)If this is common pattern (null checking), instead of having two tests each time cache dependency is required, I suggest wrapping it into Null Object Pattern and have it tested once and later simply use NOP as a dependency that can be mocked.
Edit: cache “mocking” example