1

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
}
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 2
    Does this answer your question? [Unit testing that events are raised in C# (in order)](https://stackoverflow.com/questions/248989/unit-testing-that-events-are-raised-in-c-sharp-in-order) – Peska Apr 09 '20 at 18:08
  • What do you want to test exactly. As this might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Nkosi Apr 09 '20 at 18:09
  • @Nkosi I have that a lot, when writing tests :). I want to test if my `myClass` handles a certain event correctly. – Bart Friederichs Apr 09 '20 at 18:20
  • @Peska no. That explains how to 'catch' events, not raise them. I want to raise an event in my class under test and check if the results are correct. I found the answer already though. – Bart Friederichs Apr 09 '20 at 18:27

1 Answers1

0

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
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195