Unit testing that events are raised in C# (in order)

Everything you’ve done is correct, providing you want your test to ask “What is the last event that was raised?”

Your code is firing these two events, in this order

  • Property Changed (… “My Property” …)
  • Property Changed (… “MyOtherProperty” …)

Whether this is “correct” or not depends upon the purpose of these events.

If you want to test the number of events that gets raised, and the order they get raised in, you can easily extend your existing test:

[TestMethod]
public void Test_ThatMyEventIsRaised()
{
    List<string> receivedEvents = new List<string>();
    MyClass myClass = new MyClass();

    myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
    {
        receivedEvents.Add(e.PropertyName);
    };

    myClass.MyProperty = "testing";
    Assert.AreEqual(2, receivedEvents.Count);
    Assert.AreEqual("MyProperty", receivedEvents[0]);
    Assert.AreEqual("MyOtherProperty", receivedEvents[1]);
}

Leave a Comment