【问题标题】:Lambda function causing compiler error with 0 arguments, exception with 1 or moreLambda 函数导致 0 个参数的编译器错误,1 个或更多的异常
【发布时间】: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();
}

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

【问题讨论】:

    标签: c# lambda moq xunit stub


    【解决方案1】:

    给定模拟接口的定义,只要调用.ReturnsAsync(existingList);,就会推断出类型。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多