0
I am trying to write a unit test for some code that uses IMemoryCache in controller

if(!_memoryCache.TryGetValue(cacheKey,out IEnumerable<myClass> class))
                {
                    class = await _myService.GetMyData(date, dateTo);
                    var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(_appSettings.Value.cacheDuration));
                    _memoryCache.Set(cacheKey, class, cacheEntryOptions);
                }

Note: I am trying to mock following code:.How to write unit test cases for ImemoryCache,

    _memoryCache = new Mock<IMemoryCache>();
    _memoryCache.Setup(c => c.Get(It.Is<string>(k => k == mycacheKey))).Returns(mysampleclasslist);
jubi
  • 569
  • 1
  • 10
  • 34
  • 1
    Have you been trying to mock setup `TryGetValue` instead of `Get`? – Fildor Mar 18 '22 at 11:50
  • System.NotSupportedException : Unsupported expression: x => x.TryGetValue>(It.IsAny(), TestController.<>c__DisplayClass17_0.class) Extension methods (here: CacheExtensions.TryGetValue) may not be used in setup / verification expressions. – jubi Mar 18 '22 at 12:36
  • @Fildor i get the same result here too – jubi Mar 18 '22 at 12:36
  • 1
    What IMemoryCache interface is that? Does not look like the standard one (for me that is the one from Microsoft.Extensions.Caching.Memory). But in any case you need to mock the actual used interface methode. Extension methods can't be mocked. – Ralf Mar 18 '22 at 12:46
  • Ok it is the standard one. You seem to try to mock the generic version of TryGetValue. That is an extension method and not part of the interface. You need to mock the non generic TryGetValue that is called from the TryGetValue extension method. – Ralf Mar 18 '22 at 12:48
  • And while we are at it Set (used in your code also) is also an extension method. You need to mock CreateEntry then (that called from the extension method). – Ralf Mar 18 '22 at 12:50
  • I would suggest you refer to answers and suggestions in [this question](https://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq) that may give some hints that might help you fix your issue. – Deepak-MSFT Mar 21 '22 at 09:54

0 Answers0