简体   繁体   中英

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. 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?)".

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.

I think you have to modify ClassToTest . You can have a property of type Func<string, CachedItem<T>> that gets assigned to use the extension in your class' constructor:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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