【发布时间】:2019-08-23 06:17:39
【问题描述】:
我在带有 Moq 的 C# .NET CORE 环境中使用 lambda 函数。更具体地说,我在这样的设置方法中使用它:
MockObject.Setup(o => o.GetList()).Returns<List<DifferentClass>>(() => Task.FromExisting(existingList));
问题出在 .Returns() 调用中。如果我使用空 Lambda,我会收到以下编译器错误:
error CS1593: Delegate 'Func<List<DifferentClass>, Task<List<DifferentClass>>>' does not take 0 arguments.
这意味着我需要向 lambda 添加一个参数。我这样做如下:
MockObject.Setup(o => o.GetList()).Returns<List<DifferentClass>>(o => Task.FromExisting(existingList));
现在,不是编译器错误,而是抛出异常:
System.ArgumentException : Invalid callback. Setup on method with 0 parameter(s) cannot invoke callback with different number of parameters (1).
堆栈跟踪引用同一行代码。
示例代码如下:
测试:
public class UnitTest1
{
static readonly Mock<IMyClass> MockObject;
static UnitTest1()
{
MockObject = new Mock<IMyClass>();
var existingList = new List<DifferentClass>();
// Line causing exception below
MockObject.Setup(o => o.GetList()).Returns<List<DifferentClass>>(() => Task.FromExisting(existingList));
}
// Tests go here...
[Fact]
Test1()
{
//...
}
}
这是模拟类,IMyClass:
public interface IMyClass
{
Task<List<DifferentClass>> GetList();
}
看来我的两个选择是抛出异常或编译失败。我不确定我能在这里做什么。如果有什么我遗漏的,请告诉我。
【问题讨论】: