lundi 23 mars 2020

How to mock IAppCache's GetOrAddAsync method with It.IsAny AddItemFactory function

The method I'm testing has this bit of code in it:

var devices = await _cache.GetOrAddAsync(_cacheKey, AddItemFactory, DateTimeOffset.Now.AddMinutes(Configuration.DeviceInMinutes));`

Where _cache is an IAppCache and is being mocked with a new Mock<IAppCache>(); in the test

AddItemFactory has the following signature:

private async Task<IDictionary<int, Device>> AddItemFactory()

In my test I have written:

        _appCache.Setup(x => x.GetOrAddAsync(
            It.IsAny<string>(),
            It.IsAny<Func<Task<IDictionary<int, Device>>>>(),
            It.IsAny<DateTimeOffset>())
        ).ReturnsAsync(fakeDictionary);

When that .Setup gets evaluated, my test crashes with the following error:

System.NotSupportedException : Invalid setup on an extension method: x => x.GetOrAddAsync<IDictionary<int, Device>>(It.IsAny<string>(), It.IsAny<Func<Task<IDictionary<int, Device>>>>(), It.IsAny<DateTimeOffset>())

I think it's mocked correctly because Visual Studio intellisense isn't complaining and signatures being wrong but I don't understand what is happening.

Aucun commentaire:

Enregistrer un commentaire