如何在 MSTest 中引发事件?

How to raise event in MSTest?

我正在编写测试以查看我的 class 是否对事件做出正确反应(请注意,我刚刚开始 TDD,所以请耐心等待)。

我要测试的 class 注册一个事件处理程序:

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

我的测试看起来像这样(这就是我卡住的地方):

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

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

    // Assert
}

我搞错了谁应该实施INotifyPropertyChanged。结果不是事件接收者应该实现它,而是事件发送者。不想实例化它(因为那样我会在同一个测试中测试两个 类,我认为这不是你想要的),我用 NSubstitute 来模拟它并 their documentation 给我看如何引发事件:

// 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