简体   繁体   English

使用 IMemoryCache 扩展方法的单元测试方法

[英]Unit testing method that uses IMemoryCache extension method

I am trying to write a unit test using MSTest and Moq for a method that uses an extension method of IMemoryCache.我正在尝试使用 MSTest 和 Moq 为使用 IMemoryCache 扩展方法的方法编写单元测试。 Situation:情况:

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
  }
}

How can I unit test this?我如何进行单元测试?

So far i tried:到目前为止,我尝试过:

[TestMethod]
public void TestMethodToTest()
{
  IServiceCollection services = new ServiceCollection();
  services.AddMemoryCache();

  var serviceProvider = services.BuildServiceProvider();
  var memoryCache = serviceProvider.GetService<IMemoryCache>();

  ClassToTest testClass = new ClassToTest(memoryCache);
}

This gives me the following error: "'IServiceCollection' does not contain a definition for 'AddMemoryCache' and no accessible extension method 'AddMemoryCache' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)".这给了我以下错误:“‘IServiceCollection’不包含‘AddMemoryCache’的定义,并且找不到接受‘IServiceCollection’类型的第一个参数的可访问扩展方法‘AddMemoryCache’(您是否缺少 using 指令或程序集)参考?)”。

Does anyone know how to unit test this method?有谁知道如何对这种方法进行单元测试? Preferably without changing the method itself.最好不要改变方法本身。 Is there a standard way to do this?有没有标准的方法来做到这一点? Any help is appriciated.任何帮助是appriciated。

I think you have to modify ClassToTest .我认为你必须修改ClassToTest You can have a property of type Func<string, CachedItem<T>> that gets assigned to use the extension in your class' constructor:您可以拥有一个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);
}

Then, when you want to test that class, you can override that behaviour by saying:然后,当你想测试那个类时,你可以通过说:

ClassToTest testClass = new ClassToTest(memoryCache);
testClass.GetFromCache = key => /* something else */;

Generally speaking, extension methods are still just syntactic sugar over static methods, so using them like ClassToTest does will introduce dependencies and make code harder to test in isolation.一般来说,扩展方法仍然只是静态方法之上的语法糖,因此像ClassToTest那样使用它们会引入依赖关系并使代码更难ClassToTest测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM