Recently I have had to unit test some events in an application I work on. I came up with a workable solution, but I didn’t really like the way it was working, and it just looked ugly. So I did a little digging on Google, and found this helpful question on StackOverflow.

Here is my take it. I’m putting it here so I can find easily find it again. Basically it’s the same, but I’m using a lambda to create my anonymous delegate:

public void UnitTestNodeChanged()
 var receivedEvents = new List<XmlNodeChangedEventArgs>();
 var document = new XmlDocument();

 document.NodeChanged += ((sender, e) => receivedEvents.Add(e));

 Assert.That(receivedEvents.Count, Is.EqualTo(1));

Nice and short, and to the point. We can test the fact that the event was raised (or not); how many times the event was raised; and, we can test the event arguments.

I like it. Some people may not, but it suits my purposes.