简体   繁体   English

如何设置moq模拟以引发在接口实现中定义的事件,而不是接口本身?

[英]How can I setup a moq mock to raise an event defined in an implementation of the interface and not the interface itself?

The code to be mocked looks like this: 要模拟的代码如下所示:

class Foo : IBar
{
    public virtual event EventHandler FooEventHandler;

    void FooMethod()
    {
        // blah, blah, blah...
    }

    void IBar.BarMethod()
    {
        this.FooEventHandler?.Invoke(this, new EventArgs()); 
    }
}

interface IBar 
{
    void BarMethod();
}

I want to mock Foo and its implementation of IBar so that I can hand it to the subject under test and assert. 我想模拟Foo及其IBar的实现,以便将其交给测试中的对象并进行断言。 Requirements tell me that I'm not allowed to put the event handler on the IBar interface, so the explanation behind this link doesn't seem to work for me. 需求告诉我,不允许将事件处理程序放在IBar接口上,因此此链接后面的解释似乎对我不起作用。

Edit: 编辑:

I'm trying to add clarity here, but I'm not sure it's working. 我想在这里增加清晰度,但不确定它是否有效。

Using Mock.As<T>() method allows one to create a mock that follows multiple interfaces. 使用Mock.As<T>()方法可以创建一个遵循多个接口的模拟。 With requirements that the event signature can't live on the IBar interface, I am mocking the concrete Foo class and then assigning IBar to the mock using .As<IBar>() . 由于事件签名不能存在于IBar接口上,我正在模拟具体的Foo类,然后使用.As<IBar>()IBar分配给模拟。 The return of .As<IBar> allows me to setup the .BarMethod() for raising an event with the .Raises(...) method accepting a lambda expression on the mock of IBar . .As<IBar>的返回使我可以设置.BarMethod() ,以使用.Raises(...)方法在IBar的模拟上接受lambda表达式IBar In this expression, using .As<Foo>() allows access back to the virtual event handler on the concrete being mocked withing the context of setting up IBar . 在此表达式中,使用.As<Foo>()可以访问在设置IBar的上下文中IBar的具体对象上的虚拟事件处理程序。

var foo = new Mock<Foo>();
foo.As<IBar>()
   .Setup(bar => bar.BarMethod())
   .Raises(bar => bar.As<Foo>().FooEventHandler += null, new EventArgs());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM