【问题标题】:How to mock IAppCache's GetOrAddAsync method with It.IsAny AddItemFactory function如何使用 It.IsAny AddItemFactory 函数模拟 IAppCache 的 GetOrAddAsync 方法
【发布时间】:2020-07-04 01:06:19
【问题描述】:

我正在测试的方法中有这段代码:

var devices = await _cache.GetOrAddAsync(_cacheKey, AddItemFactory, DateTimeOffset.Now.AddMinutes(Configuration.DeviceInMinutes));`

其中_cacheIAppCache,在测试中被new Mock<IAppCache>(); 模拟

AddItemFactory 具有以下签名:

private async Task<IDictionary<int, Device>> AddItemFactory()

在我的测试中我写过:

        _appCache.Setup(x => x.GetOrAddAsync(
            It.IsAny<string>(),
            It.IsAny<Func<Task<IDictionary<int, Device>>>>(),
            It.IsAny<DateTimeOffset>())
        ).ReturnsAsync(fakeDictionary);

当 .Setup 被评估时,我的测试崩溃并出现以下错误:

System.NotSupportedException : Invalid setup on an extension method: x => x.GetOrAddAsync<IDictionary<int, Device>>(It.IsAny<string>(), It.IsAny<Func<Task<IDictionary<int, Device>>>>(), It.IsAny<DateTimeOffset>())

我认为它被正确地模拟了,因为 Visual Studio 智能感知没有抱怨和签名错误,但我不明白发生了什么。

【问题讨论】:

  • IAppCache.GetOrAddAsync的签名是什么?
  • 这能回答你的问题吗? Mocking Extension Methods with Moq
  • @mm8 这是我在 _appCache.Setup 中的内容。 (字符串, Func>, DateTimeOffset)
  • @RoboKozo:如果您需要任何帮助,您需要提供更多详细信息。根据您问题中的信息,您的问题无法重现。
  • 嗯...好吧,我还可以告知该应用正在使用github.com/alastairtree/LazyCache

标签: c# testing moq


【解决方案1】:

GetOrAddAsync 方法重载是一种扩展方法;扩展方法不能被模拟。

GetOrAddAsync<T>(
      this IAppCache cache,
      string key,
      Func<Task<T>> addItemFactory,
      DateTimeOffset expires)

你需要在IAppCache接口上模拟如下方法:

Task<T> GetOrAddAsync<T>(string key, Func<ICacheEntry, Task<T>> addItemFactory);

如果您想使用 Moq 来执行此操作,库 LazyCache.Testing.Moq(免责声明 - 我是作者)通过以下设置实现此功能:

cachingServiceMock.Setup(m => m.GetOrAddAsync(
    It.IsAny<string>(),
    It.IsAny<Func<ICacheEntry, Task<T>>>()))    
    .Returns(Task.FromResult(cacheEntryValue));

其中cacheEntryValue 是调用应返回的任务结果值。

如果您不需要使用 Moq,假设您使用的是 GetOrAdd* 方法,您应该能够使用 LazyCache 库提供的内置假 (MockCachingService),根据 doco

【讨论】:

  • 我对此进行了测试,看看它是否有效并且确实有效!谢谢! FWIW 我最终只在测试中使用了“真实”缓存:new LazyCache.CachingService();
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多