views:

66

answers:

4

Hi everybody, im just starting with TDD and could solve most of the problems i've faced on my own. But now im lost: How can I check if events are fired? I was looking for something like Assert.Raise or Assert.Fire but theres nothing. Google was not very useful, most of the hits were suggestions like foo.myEvent += new EventHandler(bar); Assert.NotNull(foo.myEvent); but that proves nothing except that the world still goes round.

Thank you!

A: 

You can add your custom event handler which, for example, increments some integer field in test case class. And then check if field was incremented.

DixonD
+6  A: 

Checking if events were fires can be done by subscribing to that event and setting a boolean value:

var wasCalled = false;
foo.NyEvent += (o,e) => wasCalled = true;

...

Assert.IsTrue(wasCalled);

Due to request - without lanbdas:

var wasCalled = false;
foo.NyEvent += delegate(o,e){ wasCalled = true;}

...

Assert.IsTrue(wasCalled);
Dror Helper
haha, beat me to the punch there!
theburningmonk
You guys seem to love lambdas, every question i mark with c# 2.0 gets answered with lambda expressions :D But nevermind, thank you very much for your answer. This works well (in fact i did that before, but i thought there would be a cleaner way to go). +1
atamanroman
+1  A: 

Not really done this myself, but maybe you could add a dummy event handler to the event you wanna subscribe to and have it update a local boolean variable so that after the method is fired you can check the state of that boolean to see if the event was fired?

Something like:

bool eventFired = false;
foo.MyEvent += (s, e) => { eventFired = true };

Assert.IsTrue(eventFired);
theburningmonk
+1  A: 

@theburningmonk: A ";" is missing. Corrected version is:

bool eventFired = false;
foo.MyEvent += (s, e) => { eventFired = true; };
Assert.IsTrue(eventFired);

Cheers! ;-)

John
good catch! I'd update my answer but there's not much point as it's really a dup of Dror's answer anyway
theburningmonk