c# - 如何在只有 setter 的接口(interface)上模拟委托(delegate)的提升?

标签 c# moq

我正在尝试使用 Moq 模拟一个界面,但我不知道该怎么做。界面看起来像这样:

public delegate void MyDelegate(int i);

public interface MyInterface
{
    void Method(int i);

    MyDelegate MyDelegate { set; }
}

我正在测试一个组件,该组件将具有此接口(interface)的对象作为依赖项。我希望能够测试调用方法时引发委托(delegate)的交互,但我不知道该怎么做。我知道这是设计界面的一种有点奇怪的方式,但我无法控制它。

假设我有一个这样的类要测试:

class SystemUnderTest
{
    int i = 0;

    readonly MyInterface myInterface;

    public SystemUnderTest(MyInterface myInterface)
    {
        this.myInterface = myInterface;
        this.myInterface.MyDelegate = DelegateHandler;
    }

    public int Run(int input)
    {
        this.myInterface.Method(input);
        return i;
    }

    void DelegateHandler(int i)
    {
        this.i = i;
    }
}

我试过这样的测试,但在设置模拟时出现异常。 “ArgumentException:无法找到附加或分离方法 Void set_MyDelegate(ConsoleApp1.MyDelegate) 的事件。”

static void Main(string[] args)
{
    // Arrange
    Mock<MyInterface> mock = new Mock<MyInterface>();

    mock
        .Setup(m => m.Method(It.IsAny<int>()))
        .Raises(m => m.MyDelegate = null, 5);

    // Act
    var sut = new SystemUnderTest(mock.Object);
    var result = sut.Run(5);

    // Assert
    Trace.Assert(result == 5);
}

最佳答案

您可以这么说通过 MyDelegate 局部变量桥接您的 SystemUnderTest.DelegateHandler。尝试这样的事情:

MyDelegate del = null;

var mock = new Mock<MyInterface>();
mock.SetupSet(m => m.MyDelegate = It.IsAny<MyDelegate>())
    .Callback<MyDelegate>(d => del = d);
mock.Setup(m => m.Method(It.IsAny<int>()))
    .Callback<int>(i => del.Invoke(i));

实际上,每次调用 mock.Method 时,您的 SystemUnderTest.DelegateHandler 方法都会被调用。

关于c# - 如何在只有 setter 的接口(interface)上模拟委托(delegate)的提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54715622/

相关文章:

c# - 在 ClearCase 中检索源文件的版本号

c# - DotVVM 内部 ViewModel 中的上下文为空

c# - 挣扎于最小起订量 : The following setups were not matched

c# - 如何模拟返回 void 但修改通过 Moq 传入的引用类型的方法

c# - 最小起订量和代码契约(Contract)

c# - 设置包含对其他复杂对象的循环引用的复杂对象以进行单元测试

c# - 温莎城堡 : Register All Types in assembly using config file

c# - Entity Framework 核心更新-数据库特定迁移

c# - Moq SetupSequence 不起作用

c# - 将 PDF 流式传输到网页失败