如何使用带有EventHandler

如何使用带有EventHandler

本文介绍了如何使用带有EventHandler< T>的NSubstitute引发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义多个事件的接口,其中一些事件的委托类型为EventHandler<T>T,例如<string>.实现此接口的对象用在另一个类中,一个简单的安排如下所示:

I have an interface which defines multiple events, some with delegate type EventHandler<T> with T for example <string>. Objects implementing this interface are used in another class, a simple arrangement would look like this:

public interface IEventEmitter
{
    event EventHandler mySimpleEvent;
    event EventHandler<string> myStringEvent;
}

public class EventObserver
{
    public IEventEmitter Emitter;
    public int called = 0;
    public EventObserver(IEventEmitter emitter)
    {
        Emitter = emitter;

        Emitter.myStringEvent += (sender, text) =>
        {
            called++;
            Console.WriteLine("Observed event: {0}", text);
        };

        Emitter.mySimpleEvent += (sender, args) =>
        {
            called++;
            Console.WriteLine("Observed event: simple");
        };
        Console.WriteLine("Registered observer");
    }
}

现在,我想使用NUnit3和NSubstitute 3.1.0测试代码.使用NSubstitute,我可以用... eh ...替换这些对象,而我的代码如下:

Now I want to test the code with NUnit3 and NSubstitute 3.1.0. With NSubstitute I can substitute these objects with a ...eh... substitute, and my code looks like this:

    [Test()]
    public void EventObserverTest()
    {
        // Arrange
        IEventEmitter emitter = Substitute.For<IEventEmitter>();
        var observer = new EventObserver(emitter);
        // Act
        emitter.mySimpleEvent += Raise.Event();
// the following line doesn't work
        emitter.myStringEvent += Raise.EventWith<EventHandler<string>>("Yeah");
        // Assert
        Assert.AreEqual(2, observer.called);
    }

从替代者中提高mySimpleEvent的效果很好,但是我被困住了,无法弄清楚如何提高myStringEvent. (实际上,在代码中,我必须编写的不是字符串而是自定义类型,但我将其简化为这种形式.)

Raising mySimpleEvent from the substitute works wonderful, but I am stuck and can't figure it out how to raise myStringEvent. (Actually, in the code I have to write it is not a string but a custom Type, but I boiled it down to this form).

推荐答案

Raise.EventWith<TEventArgs>语法要求TEventArgs派生(请参见).

The Raise.EventWith<TEventArgs> syntax requires T to derive from EventArgs (see source).

要与非EventArgs和我们可以使用的其他委托类型一起使用,可以使用Raise.Event<TDelegate>,如引发Delegate事件:

To work with non-EventArgs and other delegate types we can use can use Raise.Event<TDelegate> as described in Raising Delegate events:

// Arrange
IEventEmitter emitter = Substitute.For<IEventEmitter>();
var observer = new EventObserver(emitter);
// Act
emitter.mySimpleEvent += Raise.Event();
emitter.myStringEvent += Raise.Event<EventHandler<string>>(this, "Yeah");
// Assert
Assert.AreEqual(2, observer.called);

这篇关于如何使用带有EventHandler&lt; T&gt;的NSubstitute引发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:59