模拟扩展方法会导致System.NotSupportedException [英] Mocking of extension method result in System.NotSupportedException
问题描述
我正在对使用IMemoryCache
接口的ClientService进行单元测试:
I'm unit testing a ClientService that uses the IMemoryCache
interface:
ClientService.cs:
ClientService.cs:
public string Foo()
{
//... code
_memoryCache.Set("MyKey", "SomeValue", new TimeSpan(0, 0, 60));
}
当我尝试使用以下方法模拟IMemoryCache
的Set
扩展名时:
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());
它抛出以下异常:
System.NotSupportedException:不支持的表达式:x => x.Set(It.IsAny(),It.IsAny(), It.IsAny()) 扩展方法(在这里:CacheExtensions.Set)可能无法在设置/验证前使用
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
对其进行模拟.您可以嘲笑的是扩展方法本身使用的方法...
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...
在您的情况下,Set
使用CreateEntry
,这是IMemoryCache
定义的方法,可能会被嘲笑.尝试这样的事情:
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>);
这篇关于模拟扩展方法会导致System.NotSupportedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!