Unit Testing Events With Anonymous Delegates

I’ve been ramping up the amount of unit testing I’ve been doing lately, and whenever I had to do unit tests I would create the normal event handler and do the assertion in the handler.

But the problem with this approach is that (in my opinion) it can be really messy with a whole bunch of handlers for each event thrown in each test. Anonymous delegates get around this get around this because the handler can be done inline with the actual test.

[Test]
public void SettingValueRaisesEventTest() {
bool eventRaised = false;
Parameter param = new Parameter("num", "int", "1");
param.ValueChanged +=
delegate(object sender, ValueChangedEventArgs e) {
Assert.AreEqual("42", e.NewValue);
Assert.AreEqual("1", e.OldValue);
Assert.AreEqual("num", e.ParameterName);
eventRaised = true;
};

param.Value = "42"; //should fire event.

Assert.IsTrue(eventRaised, "Event was not raised");
}

In general, I try not to use anonymous delegates, especially when the delegate contains a lot of code. I think they can become confusing and hard to read. But this is a situation in which I think using an anonymous delegate is particularly handy.

Leave a Reply

Your email address will not be published. Required fields are marked *