Search code examples
c#eventstddmstestnsubstitute

How to raise event in MSTest?


I am writing a test to see if my class reacts correctly to an event (and mind you, I just started TDD, so bear with me).

The class I want to test against registers an event handler:

class MyClass {
       public MyClass(INotifyPropertyChanged propertyChanged) {
            propertyChanged.PropertyChanged += MyHandler;
       }
}

and my test looks something like this (this is where I am stuck):

[TestMethod]
public void MyClass_ShouldHandleEventCorrectly() {
    // Arrange
    MyClass myClass = new MyClass();

    // Act (this obviously doesn't work ....)
    myClass.PropertyChanged.Invoke()

    // Assert
}

Solution

  • I was mistaken in who should implement INotifyPropertyChanged. Turns out not the event receiver should implement it, but the event sender. Not wanting to instantiate that (because then I would test two classes in the same test, which I think is not what you want), I used NSubstitute to mock it and their documentation showed me how to raise the event:

    // Arrange
    INotifyPropertyChanged notifyPropertyChanged = Substitute.For<INotifyPropertyChanged>();
    MyClass myClass = new MyClass(notifyPropertyChanged);
    
    // Act
    notifyPropertyChanged += Raise.Event<PropertyChangedEventHandler>(notifyPropertyChanged, new PropertyChangedEventHandlerArgs("property"));
    
    // Assert
    ... check whatever needed in myClass