views:

1705

answers:

2
+19  A: 

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]);
}
Andrew Stapleton
Thanks, that's exactly what I was after - didn't know that I could use a list like that to handle the events.
David Hall
Hehe, thanks for this so old but useful answer. It have prevented me of writing a question.
zerkms
+1  A: 

If you're doing TDD then event testing can start to generate a lot of repetitive code. I wrote an event monitor that enables a much cleaner approach to unit test writing for these situations.

var publisher = new PropertyChangedEventPublisher();

Action test = () =>
{
    publisher.X = 1;
    publisher.Y = 2;
};

var expectedSequence = new[] { "X", "Y" };

EventMonitor.Assert(test, publisher, expectedSequence);

Please see my answer to the following for more details.

http://stackoverflow.com/questions/2567047/unit-testing-that-an-event-is-raised-in-c-using-reflection/2697721#2697721

Or a series of blog articles I posted about it:

http://gojisoft.com/blog/2010/04/22/event-sequence-unit-testing-part-1/

chibacity