redis stringsetasync在使用moq的单元测试中返回false

v1uwarro  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(668)

我目前正在为解决方案的redisprovider类编写单元测试。我的类中有一个方法在redis缓存中设置一个键:

public async Task<bool> StringSetAsync(string key, string value)
{
   var cache = multiplexer.GetDatabase();
   //Some other stuff
   result = await cache.StringSetAsync(key, value);
   return result;
}

在单元测试中,我有以下设置:

var mockMultiplexer = new Mock<IConnectionMultiplexer>();

   mockMultiplexer.Setup(_ => _.IsConnected).Returns(true);
   mockMultiplexer.Setup(_ => _.Configuration).Returns(MockedData.CacheConnectionString);

   var mockDatabase = new Mock<IDatabase>();

   mockMultiplexer
         .Setup(_ => _.GetDatabase(It.IsAny<int>(), It.IsAny<object>()))
         .Returns(() => mockDatabase.Object);

   RedisCacheProvider mockedCacheProvider = new RedisCacheProvider(new Mock<ILogger<RedisCacheProvider>> 
 ().Object, mockMultiplexer.Object);

   var result = await mockedCacheProvider.StringSetAsync(It.IsAny<string>(), It.IsAny<string>());

当我为我的单元测试运行上面的代码时,我收到的结果总是错误的。有没有办法得到真正的结果?这里怎么了?

vltsax25

vltsax251#

我意识到这应该由使用类的服务来模拟,而不是在类本身上验证。
干得好:

mockedCacheProvider.Setup(h => h.StringSetAsync(
                 It.IsAny<string>(),
                 It.IsAny<string>())).ReturnsAsync(() => true);

相关问题