Moq Returns 方法未按预期工作
Moq Returns method not working as expected
看看这段代码:
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
的 return 设置为一个简单的非 empty/null 字符串。
我的问题是,在 caching.GetKeyAsync
中,对该方法的调用是 return 一个空结果。我在这里做错了什么?
GetKeyAsync 代码:
result = _thirdLevelCache.StringGetAsync(key, CommandFlags.None).ContinueWith((prev) =>
{
string res = null;
if (!prev.Result.IsNull)
{
res = prev.Result.ToString();
}
return res as object;
});
尝试使用 async/await 和 Moq 的 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);
}
我用 It.IsAny<RedisKey>()
替换了 It.IsAny<string>()
看看这段代码:
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
的 return 设置为一个简单的非 empty/null 字符串。
我的问题是,在 caching.GetKeyAsync
中,对该方法的调用是 return 一个空结果。我在这里做错了什么?
GetKeyAsync 代码:
result = _thirdLevelCache.StringGetAsync(key, CommandFlags.None).ContinueWith((prev) =>
{
string res = null;
if (!prev.Result.IsNull)
{
res = prev.Result.ToString();
}
return res as object;
});
尝试使用 async/await 和 Moq 的 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);
}
我用 It.IsAny<RedisKey>()
It.IsAny<string>()