Unit Testing Best Practices – Methods Using Cache

cachingunit testing

I have a number of business logic methods that store and retrieve (with filtering) objects and lists of objects from cache.

Consider

IList<TObject> AllFromCache() { ... }

TObject FetchById(guid id) { ... }

IList<TObject> FilterByPropertry(int property) { ... }

Fetch.. and Filter.. would call AllFromCache which would populate cache and return if it isn't there and just return from it if it is.

I generally shy away from unit testing these. What are best practices for Unit Testing against this type of structure?

I considered populating cache on TestInitialize and removing on TestCleanup but that doesn't feel right to me, (tho it could well be).

Best Answer

If you want true Unit Tests, then you have to mock the cache: write a mock object that implements the same interface as the cache, but instead of being a cache, it keeps track of the calls it receives, and always returns what the real cache should be returning according to the test case.

Of course the cache itself also needs unit testing then, for which you have to mock anything it depends on, and so on.

What you describe, using the real cache object but initializing it to a known state and cleaning up after the test, is more like an integration test, because you are testing several units in concert.

Related Topic