简体   繁体   中英

How to raise an event with NSubstitute with EventHandler<T>?

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");
    }
}

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); 
    } 

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).

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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