I\'m trying to implement a unit test for a function in a project that doesn\'t have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I\'ve
When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.
Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.
public interface ICacheWrapper
{
...methods to support
}
public class CacheWrapper : ICacheWrapper
{
private System.Web.Caching.Cache cache;
public CacheWrapper( System.Web.Caching.Cache cache )
{
this.cache = cache;
}
... implement methods using cache ...
}
public class MockCacheWrapper : ICacheWrapper
{
private MockCache cache;
public MockCacheWrapper( MockCache cache )
{
this.cache = cache;
}
... implement methods using mock cache...
}
public class MockCache
{
... implement ways to set mock values and retrieve them...
}
[Test]
public void CachingTest()
{
... set up omitted...
ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );
CacheManager manager = new CacheManager( wrapper );
manager.Insert(item,value);
Assert.AreEqual( value, manager[item] );
}
Real code
...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...