无法使用 lambda 表达式设置没有参数的函数
Cannot setup the function with out parameter using lambda expression
我在错误消息中发现了很多问题,但没有一个符合我的具体情况。
我在缓存实现中有一个带有此签名的方法:
public bool TryGet(TKey key, out TValue returnVal, Func<TKey, TValue> externalFunc = null)
我有一个 class 从 TKey : CompositeKey 和 TValue : string.
我正在尝试像这样模拟它进行单元测试:
_cacheMock
.Setup(x => x.TryGet(It.IsAny<CompositeKey>(), out It.Ref<string>.IsAny, It.IsAny<Func<CompositeKey, string>>()))
.Returns((CompositeKey key, out string s, Func<CompositeKey, string> fetchOne) => { s = ""; return true; });
我收到 .Returns
行的编译错误:
"Cannot convert lambda expression to type 'bool' because it is not a
delegate type"
如果我删除 "out" 修饰符,它编译正常 - 但当然不匹配调用的签名,我无法获取输出值。
有没有办法在不修改 TryGet() 方法本身的情况下修复语句的 Returns() 部分?
这可能适合你:
//define the callback delegate
delegate void TryGetCallback(CompositeKey key, out string str, Func<CompositeKey, string> func);
mock.Setup(x => x.TryGet(
It.IsAny<CompositeKey>(),
out It.Ref<string>.IsAny,
It.IsAny<Func<CompositeKey, string>>()))
.Callback(new TryGetCallback((CompositeKey key, out string str, Func<CompositeKey, string> func) =>
{
str = "foo bar";
}))
.Returns(true);
通过这样的设置,您可以存档您想要的内容
string actualValue;
bool result = mock.Object.TryGet(new CompositeKey(), out actualValue)
//actualValue = "foo bar", result = true
我在错误消息中发现了很多问题,但没有一个符合我的具体情况。
我在缓存实现中有一个带有此签名的方法:
public bool TryGet(TKey key, out TValue returnVal, Func<TKey, TValue> externalFunc = null)
我有一个 class 从 TKey : CompositeKey 和 TValue : string.
我正在尝试像这样模拟它进行单元测试:
_cacheMock
.Setup(x => x.TryGet(It.IsAny<CompositeKey>(), out It.Ref<string>.IsAny, It.IsAny<Func<CompositeKey, string>>()))
.Returns((CompositeKey key, out string s, Func<CompositeKey, string> fetchOne) => { s = ""; return true; });
我收到 .Returns
行的编译错误:
"Cannot convert lambda expression to type 'bool' because it is not a delegate type"
如果我删除 "out" 修饰符,它编译正常 - 但当然不匹配调用的签名,我无法获取输出值。
有没有办法在不修改 TryGet() 方法本身的情况下修复语句的 Returns() 部分?
这可能适合你:
//define the callback delegate
delegate void TryGetCallback(CompositeKey key, out string str, Func<CompositeKey, string> func);
mock.Setup(x => x.TryGet(
It.IsAny<CompositeKey>(),
out It.Ref<string>.IsAny,
It.IsAny<Func<CompositeKey, string>>()))
.Callback(new TryGetCallback((CompositeKey key, out string str, Func<CompositeKey, string> func) =>
{
str = "foo bar";
}))
.Returns(true);
通过这样的设置,您可以存档您想要的内容
string actualValue;
bool result = mock.Object.TryGet(new CompositeKey(), out actualValue)
//actualValue = "foo bar", result = true