我正在对使用IMemoryCache
接口的客户端服务进行单元测试:
客户服务.cs:
public string Foo()
{
//... code
_memoryCache.Set("MyKey", "SomeValue", new TimeSpan(0, 0, 60));
}
当我试图用以下方法嘲笑IMemoryCache
的Set
扩展时:
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: 不支持的表达式: x =>x.Set(It.IsAny((, It.IsAny((, It.IsAny((( 扩展方法(此处:CacheExtensions.Set(不得用于设置/验证 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>);