【发布时间】:2017-07-11 21:13:20
【问题描述】:
我正在尝试使用 Moq 模拟 IMemoryCache。我收到此错误:
“System.NotSupportedException”类型的异常发生在 Moq.dll 但未在用户代码中处理
附加信息:表达式引用的方法不 属于模拟对象:x => x.Get
(It.IsAny ())
我的模拟代码:
namespace Iag.Services.SupplierApiTests.Mocks
{
public static class MockMemoryCacheService
{
public static IMemoryCache GetMemoryCache()
{
Mock<IMemoryCache> mockMemoryCache = new Mock<IMemoryCache>();
mockMemoryCache.Setup(x => x.Get<string>(It.IsAny<string>())).Returns("");<---------- **ERROR**
return mockMemoryCache.Object;
}
}
}
为什么会出现这个错误?
这是正在测试的代码:
var cachedResponse = _memoryCache.Get<String>(url);
其中_memoryCache 的类型为IMemoryCache
如何模拟上面的_memoryCache.Get<String>(url) 并让它返回null?
编辑:如果不是_memoryCache.Set<String>(url, response);,我将如何做同样的事情?我不介意它返回什么,我只需要将方法添加到模拟中,这样它就不会在调用时抛出。
按照我尝试过的这个问题的答案:
mockMemoryCache
.Setup(m => m.CreateEntry(It.IsAny<object>())).Returns(null as ICacheEntry);
因为在 memoryCache 扩展中它显示它在 Set 内使用 CreateEntry。但它出错了“对象引用未设置为对象的实例”。
【问题讨论】:
标签: c# unit-testing asp.net-core .net-core moq