Reputation: 82507
I have a class that looks similar to this:
public class DiscoveryDocumentCache
{
static DiscoveryDocumentCache()
{
cache = new MemoryCache(discoveryDocumentCacheName);
}
private static MemoryCache cache;
// Other stuff...
}
I want the memory cache to be static so that it is shared across all instances of the class.
It is working great for the actual use cases. Where I am struggling is with my unit tests. Because the cache
variable is static, it accumulates all the different values that get put in it.
My use case does not have a "remove" option. (They just expire out of the cache.)
I have added this to my DiscoveryDocumentCache
class:
public void __UnitTesting__CleanUpMemoryCacheBetweenTests()
{
cache.Dispose();
cache = new MemoryCache(discoveryDocumentCacheName);
}
But it feels dirty to add a method that is just to facilitate unit testing.
.NET Framework had some ways to access class's private variables if you really thought you should. Is there something similar I can do to reset this static variable in my TearDown
unit test method?
Upvotes: 0
Views: 2681
Reputation: 13736
Not sure if you'll think this is an answer, or just a long comment. :-)
Your tests are working well because they are telling you something. They're saying "This is a bad use of a static instance."
Statics are always suspicious, although not always bad. What's bad here is you use a static to implement the singleton pattern in a way that is subsequently out of your control. That is, your individual instances are deciding for themselves which cache (the singleton) to use, rather than being told what to use.
As @Vaccano suggests, you are better off to use some sort of dependency injection. Translate that to "Tell each object what cache to use rather than having them figure it out for itself." This is one of those things that requires a bit of up-front investment in order to avoid saving trouble later.
As an aside... there is nothing wrong with changing your application to make it more testable. Testability is just another of those "ilities" that define good software design. The trick is to change it so as to improve the software, usually simplifying it rather than complicating it.
Upvotes: 1