Friday, July 06, 2007

Tip:#1 Testing Events in C#

If you have a class that causes a .Net event to fire. When writing a test for the event, you can add a handler to the event that sets a flag that you then assert on in your code. Using normal delegates means the variable would need to be a class member and get initialized in Setup. Use of anonymous delegates cleans this up nicely.

[Test]
public void TriggerEvent_CausesEventThatFiresToFire()
{
Customer customer = new Customer("Ben");
string changedPropertyName = null;

customer.PropertyChanged += delegate(object sender, PropertyChangedEventArgs args)
{changedPropertyName = args.PropertyName;};

customer.Name = "Kate";

Assert.AreEqual("Kate",changedPropertyName);
}

2 comments:

Anonymous said...

Wouldn't this fail if you're unit testing events that are set off in a different thread? For example, you fire an async operation that needs to perform some calculation. After you do this calculation you fire an event to let the caller know it finished. This approach would be useless wouldn't it?

Nigel Thorne said...

I would test a few things there.

1. Does my code fire off the calculation without blocking?

2. Does my calling code respond correctly to the event signifying the calculation is complete?

3. Does the calculation code fire the event on an injected object when it has finished?

Testing these things separately means you are testing the calculation code without having to deal with threads. In this case the tip I suggest would work well.

GitHub Projects