简体   繁体   中英

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
}

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

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