模拟扩展方法导致 System.NotSupportedException

Mocking of extension method result in System.NotSupportedException

我正在对使用 IMemoryCache 接口的 ClientService 进行单元测试:

ClientService.cs:

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

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

当我尝试模拟 IMemoryCacheSet 扩展时:

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

它抛出一个异常:

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

这是命名空间的缓存扩展Microsoft.Extensions.Caching.Memory

public static class CacheExtensions
{
   public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow);
}

扩展方法实际上是静态方法,不能使用 moq 模拟它们。您可以模拟的是扩展方法本身使用的方法...

在你的情况下 Set 使用 CreateEntry 这是 IMemoryCache 定义的方法,它可以被模拟。尝试这样的事情:

memoryCacheMock
    .Setup(x => x.CreateEntry(It.IsAny<object>()))
    .Returns(Mock.Of<ICacheEntry>);