Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a System.Web.Caching.Cache object in a unit test

Tags:

c#

asp.net

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 been trying to create this object by using code such as...

System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);

...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.

How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?

like image 738
Guy Avatar asked Oct 28 '08 18:10

Guy


1 Answers

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);

...
like image 82
tvanfosson Avatar answered Nov 11 '22 13:11

tvanfosson