You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法使用Moq模拟Redis IDatabase接口的问题求助

无法使用Moq模拟Redis IDatabase接口的问题求助

各位大佬好,我正在给程序里的缓存模块写单元测试,想用Moq模拟Redis的IDatabase接口,但测试一直达不到预期效果,实在搞不定了,来求助大家🙏

以下是我的测试代码:

[Fact]
public async Task Cache_Works_Correctly()
{
    const string testkey = "69";
    const string testvalue = "Nice";

    var mockDatabase = new Mock<IDatabase>();
  
    mockDatabase.Setup<string>(_ => _.StringGet(CacheConstants.NamePrefix + testkey, CommandFlags.None)).Returns(testvalue);

    var mockMultiplexer = new Mock<IConnectionMultiplexer>();
    mockMultiplexer.Setup(_ => _.IsConnected).Returns(false);

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

    var cache = new CacheStore(mockMultiplexer.Object.GetDatabase(), new Mock<ILogger<CacheStore>>().Object);

 
    Assert.Equal(testvalue, await cache.GetValueAsync<string>(testkey));
}

问题就出在这一行:

mockDatabase.Setup<string>(_ => _.StringGet(CacheConstants.NamePrefix + testkey, CommandFlags.None)).Returns(testvalue);

我本来预设了当调用StringGet方法传入拼接后的键和CommandFlags.None时,返回testvalue,但实际运行测试时这个预设好像没生效,断言总是失败。有没有大佬能帮我排查下哪里出问题了?

备注:内容来源于stack exchange,提问作者HellAbyss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 15:33:04