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

问题描述 投票:3回答:1

我在使用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个回答
3
投票

给定模拟接口的定义,只需调用.ReturnsAsync(existingList);并推断类型。

static UnitTest1()
{
    MockObject = new Mock<IMyClass>();
    var existingList = new List<DifferentClass>();
    MockObject
        .Setup(o => o.GetList())
        .ReturnsAsync(existingList);
}
© www.soinside.com 2019 - 2024. All rights reserved.