Lambda 函数导致带有 0 个参数的编译器错误,带有 1 个或多个参数的异常

Lambda function causing compiler error with 0 arguments, exception with 1 or more

我在带有 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()
    {
        //...
    }
}

这是模拟的 class, IMyClass:

public interface IMyClass
{
    Task<List<DifferentClass>> GetList();
}

看来我的两个选择是抛出异常或编译失败。我不确定我能在这里做什么。如果有任何遗漏,请告诉我。

根据模拟接口的定义,只需调用 .ReturnsAsync(existingList); 即可推断类型。

static UnitTest1()
{
    MockObject = new Mock<IMyClass>();
    var existingList = new List<DifferentClass>();
    MockObject
        .Setup(o => o.GetList())
        .ReturnsAsync(existingList);
}