DarthVader
DarthVader

Reputation: 55122

How to test a CacheProvider

I have a Cache class as follows:

public class MyCache : ICacheProvider
{ 
    private readonly IMemoryCache _cache; 
    private readonly MemoryCacheOptions _options;
    private readonly ILogger<InMemoryCacheProvider> _logger;  

    public MyCache(IMemoryCache cache, MemoryCacheOptions options, ILogger<InMemoryCacheProvider> logger)
    {
      //Elided
    }

    public virtual void Set<T>(string key, T value, TimeSpan expiration) where T : class
    {  
        _cache.Set(key, value, expiration); 
    } 

    public virtual T Get<T>(string key) where T : class
    { 
        if (_cache.Get(key) is T result)
        { 
            return result; 
        }  
        return default(T);
    } 
    // removed some code for clarity
 }

ICacheProvider has methods like Set and Get.

Well how can I test this class? I need to test that set method actually sets something to the depencency. With FakeitEasy I have done the following:

    [Fact]
    public void SetTest()
    {
        var cache = A.Fake<MyCache>();
        var item = A.Fake<TestClass>();
        cache.Set("item", item);

        A.CallTo(() => cache.Set("item", item)).MustHaveHappened(); 
    }

But this didnt make too much sense to me.

What I am interested is, when I call the set method, I need to be able to check if there is really an object set in the fake cache or whatever. Same for Get and other methods.

Can you please elaborate?

Upvotes: 0

Views: 1117

Answers (1)

Blair Conrad
Blair Conrad

Reputation: 242120

@Nkosi's comment is correct. A mocking framework is used by mocking the system under test's collaborators. Then the system under test can be exercised. Like this:

// mock a collaborator
var fakeCache = A.Fake<IMemoryCache>();

// Create a real system under test, using the fake collaborator.
// Depending on your circumstances, you might want real options and logger,
// or fake options and logger. For this example, it doesn't matter.
var myCacheProvider = new MyCache(fakeCache, optionsFromSomewhere, loggerFromSomewhere);

// exercise the system under test
myCacheProvider.Set("item", item, someExpriation);

// use the fake collaborator to verify that the system under test worked
// As @Nkosi points out, _cache.Set(key, value, expiration)
// from the question is an extension method, so you can't assert on it
// directly. Otherwise you could do
// A.CallTo(() => fakeCache.Set("item", item, expiration)).MustHaveHappened();
// Instead you'll need to assert on CreateEntry, which could be a little trickier

Upvotes: 3

Related Questions