I have this CacheManager class which keeps a static dictionary with all sorts of cached data. However, with this dictionary being static it gets filled up with data from the other unit tests. This keeps me from unit testing whether or not the CacheManager is empty on init, and breaks with the principles of unit testing.
Any ideas how to create a proper unit test for this?
Code
public class CacheManager
{
private static readonly Dictionary<ICacheKey, ListCacheItem> cacheEntries =
new Dictionary<ICacheKey, ListCacheItem>();
public static Dictionary<ICacheKey, ListCacheItem> CacheEntries
{
get
{
lock (cacheEntries)
{
return cacheEntries;
}
}
}
Generally, this is not a good idea from a testing perspective. By making the members of
CacheManagerstatic, you will never be able to isolate it in such a way to make it nice to unit test.Perhaps a better solution is the Singleton Pattern. To do this, get rid of the static modifiers on
CacheManager‘s members. Then you can have one static instance in your app that is used by everyone else. Therefore, in your unit test, you could create a new instance of the class that you can test in isolation, but still have the desired functionality.