gpt4 book ai didi

c# - 使用 Moq 实例引发 EventHandler 事件

转载 作者:太空狗 更新时间:2023-10-29 22:22:18 24 4
gpt4 key购买 nike

我有接口(interface)

public interface IBar
{

}

public interface IFoo
{
event EventHandler<IBar> MyEvent;
}

和一个类

public class Foobar
{
public Foobar(IFoo foo)
{
foo.MyEvent += MyEventMethod;
}

private void MyEventMethod(object sender, IBar bar)
{
// do nothing
}
}

现在我想使用 Moq 4 对这段出色的代码进行单元测试:

[Test]
public void MyTest()
{
Mock<IFoo> foo = new Mock<IFoo>();
Mock<IBar> bar = new Mock<IBar>();

Foobar foobar = new Foobar(foo.Object);

foo.Raise(e => e.MyEvent += null, bar.Object);
}

根据我的理解,Foobar.MyEventMethod 应该通过 raise 来调用。发生的情况是我收到一个运行时异常,显示 System.Reflection.TargetParameterCountEception {"Parameter count mismatch."}。

有趣的是:当我在单元测试中提出以下内容时:

foo.Raise(e => e.MyEvent += null, EventArgs.Empty, bar.Object);

一切如我所愿。谁能解释为什么调用需要三个参数?

谢谢

最佳答案

我假设您当时使用的是 .NET 4.5。 Type constraint was removed from EventHandler<TEventArgs> 它允许你做这样的事情:

event EventHandler<IBar> MyEvent;

在哪里IBar只是一些接口(interface)

IN 4.0,具有约束限制 TEventArgs可分配给 EventArgs类型,您的代码将无法编译。

因此(IBar 不是从 EventArgs 派生的),Moq 不会将您的事件视为 "corresponding to Event Handler pattern" ,并将其视为任何其他委托(delegate):

// Raising a custom event which does not adhere to the EventHandler pattern
...
// Raise passing the custom arguments expected by the event delegate
mock.Raise(foo => foo.MyEvent += null, 25, true);

这意味着您必须提供所有参数,包括发件人

关于c# - 使用 Moq 实例引发 EventHandler<TEventArgs> 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147168/

24 4 0