使用 lambda 表达式设置方法

3

我正在尝试通过相应的Lambda表达式在实例上伪造一个方法:

private void TranslateCallbackToSetup<TResult>(Mock<TService> stubService, IMethodCall<TService,TResult> methodCall)
{
    stubService.Setup(t => methodCall.RunMethod(t)).Returns(() =>
    {                
         return default(TResult);
    });
}

public interface IMethodCall<in TService, out TResult> : IMethodCall where TService : class
{
    Func<TService, TResult> RunMethod { get; }
}

语法似乎没问题,但代码出现了ArgumentException:

表达式不是方法调用:t => t

有什么想法吗?

1个回答

3
这失败是因为您正在尝试在除了模拟本身之外的其他地方设置方法。您想要在RunMethod方法使用stubService作为参数时,使您的IMethodCall实例返回特定值。在这种情况下,您需要传入一个模拟IMethodCall,因为这是您要定义行为的对象。
如果您查看这里的示例,您将看到所有被模拟的方法都是模拟上的方法。因此,如果您可以重构您的TService类型以接受方法调用,您可能会使它工作。
在您的服务上。
public IService 
{
     TResult ExecuteMethodCall(IMethodCall<IService, TResult>);
}

在你的测试中,然后...
stubService.Setup(t => t.ExecuteMethodCall(methodCall))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接