14

I'm unit testing a ClientService that uses the IMemoryCache interface:

ClientService.cs:

public string Foo()
{        
    //... code

    _memoryCache.Set("MyKey", "SomeValue", new TimeSpan(0, 0, 60));
}

When I try to mock the IMemoryCache's Set extension with:

AutoMock mock = AutoMock.GetLoose();

var memoryCacheMock = _mock.Mock<IMemoryCache>();

string value = string.Empty;

// Attempt #1:
memoryCacheMock
     .Setup(x => x.Set<string>(It.IsAny<object>(), It.IsAny<string>(), It.IsAny<TimeSpan>()))
     .Returns("");

// Attempt #2:
memoryCacheMock
    .Setup(x => x.Set(It.IsAny<object>(), It.IsAny<object>(), It.IsAny<TimeSpan>()))
    .Returns(new object());

It throw an exception of:

System.NotSupportedException: Unsupported expression: x => x.Set(It.IsAny(), It.IsAny(), It.IsAny()) Extension methods (here: CacheExtensions.Set) may not be used in setup / verification ex

This is the Cache extension of the namespace Microsoft.Extensions.Caching.Memory

public static class CacheExtensions
{
   public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow);
}
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • 1
    You cannot mock extension method, I guess behind the `Set` is actually `CreateEntry` which actually should have been mocked... – Johnny Aug 29 '19 at 07:48
  • 1
    Extension methods are static - you can't mock static methods. There are some tools that let you replace them, I think, but that's not the right approach IMHO. See [here](https://stackoverflow.com/questions/12580015/how-to-mock-static-methods-in-c-sharp-using-moq-framework). – ProgrammingLlama Aug 29 '19 at 07:52

1 Answers1

38

Extension methods are actually static methods and they cannot be mocked using moq. What you could mock are the methods used by the extension method itself...

In your case Set uses CreateEntry which is the method defined by IMemoryCache and it could be mocked. Try something like this:

memoryCacheMock
    .Setup(x => x.CreateEntry(It.IsAny<object>()))
    .Returns(Mock.Of<ICacheEntry>);
Johnny
  • 8,939
  • 2
  • 28
  • 33