[英]Unit testing method that uses IMemoryCache extension method
我正在尝试使用 MSTest 和 Moq 为使用 IMemoryCache 扩展方法的方法编写单元测试。 情况:
public class ClassToTest
{
private IMemoryCache Cache { get; }
public ClassToTest(IMemoryCache cache)
{
Cache = cache;
}
public async Task<SomeType> MethodToTest(string key)
{
// Get is an extension method defined in Microsoft.Extensions.Caching.Memory
var ci = Cache.Get<CachedItem<T>>(key);
// Do stuff with cached item
}
}
我如何进行单元测试?
到目前为止,我尝试过:
[TestMethod]
public void TestMethodToTest()
{
IServiceCollection services = new ServiceCollection();
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var memoryCache = serviceProvider.GetService<IMemoryCache>();
ClassToTest testClass = new ClassToTest(memoryCache);
}
这给了我以下错误:“‘IServiceCollection’不包含‘AddMemoryCache’的定义,并且找不到接受‘IServiceCollection’类型的第一个参数的可访问扩展方法‘AddMemoryCache’(您是否缺少 using 指令或程序集)参考?)”。
有谁知道如何对这种方法进行单元测试? 最好不要改变方法本身。 有没有标准的方法来做到这一点? 任何帮助是appriciated。
我认为你必须修改ClassToTest
。 您可以拥有一个Func<string, CachedItem<T>>
类型的属性,该属性被分配为在类的构造函数中使用扩展:
public Func<string, CachedItem<T>> GetFromCache { get; set; }
public ClassToTest(IMemoryCache cache)
{
Cache = cache;
GetFromCache = key => Cache.Get<CachedItem<T>>(key);
}
然后,当你想测试那个类时,你可以通过说:
ClassToTest testClass = new ClassToTest(memoryCache);
testClass.GetFromCache = key => /* something else */;
一般来说,扩展方法仍然只是静态方法之上的语法糖,因此像ClassToTest
那样使用它们会引入依赖关系并使代码更难ClassToTest
测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.