【问题标题】:Cannot setup the function with out parameter using lambda expression无法使用 lambda 表达式设置带有 out 参数的函数
【发布时间】:2019-02-14 11:56:08
【问题描述】:

我发现了很多关于错误消息的问题,但没有一个与我的具体情况相符。

我在缓存实现中有一个带有此签名的方法:

public bool TryGet(TKey key, out TValue returnVal, Func<TKey, TValue> externalFunc = null)

我有一个派生自 TKey 的类:CompositeKey 和 TValue:字符串。

我正在尝试模拟它以进行这样的单元测试:

_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 行的编译错误:

"无法将 lambda 表达式转换为类型 'bool',因为它不是 委托类型”

如果我删除“out”修饰符,它编译正常 - 但当然与调用的签名不匹配,我无法得到 out 值。

有没有办法在不修改 TryGet() 方法本身的情况下修复语句的 Returns() 部分?

【问题讨论】:

    标签: c# lambda moq


    【解决方案1】:

    这可能对你有用:

    //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
    

    【讨论】:

    • 感谢您提供使用我自己的代码构建的示例,是的,它实际上可以编译并正常工作!好东西!
    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2010-11-24
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2018-02-09
    相关资源
    最近更新 更多