Moq返回方法无法按预期工作

时间:2017-01-30 17:56:54

标签: c# unit-testing mocking moq azure-redis-cache

看看这段代码:

var thirdLevelCacheMock = new Mock<IDatabase>();
RedisValue val = "not empty or null string";
thirdLevelCacheMock.Setup(m => m.StringGetAsync(It.IsAny<string>(), It.IsAny<CommandFlags>())).Returns(Task.FromResult(val));

CachingInfrastructure caching = new CachingInfrastructure();
caching._thirdLevelCache = thirdLevelCacheMock.Object;

var operation = caching.GetKeyAsync("bla", CacheLevel.Any);

Assert.DoesNotThrow(() => { operation.Wait(); });
Assert.IsNotNull(operation.Result);

您可以注意到,我将StringGetAsync的返回值设置为一个简单的非空/空字符串。

我的问题是,在caching.GetKeyAsync内,对该方法的调用返回null结果。我在这里做错了什么?

GetKeyAsync代码:

result = _thirdLevelCache.StringGetAsync(key, CommandFlags.None).ContinueWith((prev) =>
      {
            string res = null;
            if (!prev.Result.IsNull)
            {
               res = prev.Result.ToString();
            }
            return res as object;
      });

2 个答案:

答案 0 :(得分:1)

尝试使用asq / await与Moq&#39; ResturnsAsync进行测试,而不是使用阻止调用.Wait()

public async Task TestMthod() {
    //Arrange
    var expected = "not empty or null string";
    var thirdLevelCacheMock = new Mock<IDatabase>();
    RedisValue val = expected;
    thirdLevelCacheMock
        .Setup(m => m.StringGetAsync(It.IsAny<string>(), It.IsAny<CommandFlags>()))
        .ReturnsAsync(val);

    var caching = new CachingInfrastructure();
    caching._thirdLevelCache = thirdLevelCacheMock.Object;

    //Act
    var actual = await caching.GetKeyAsync("bla", CacheLevel.Any);

    //Assert
    Assert.IsNotNull(actual);
    Assert.AreEqual(expected, actual);
}

答案 1 :(得分:1)

我将It.IsAny<string>()替换为It.IsAny<RedisKey>()