Test events with nunit

atamanroman picture atamanroman · Aug 2, 2010 · Viewed 20.1k times · Source

I'm just starting with TDD and could solve most of the problems I've faced on my own. But now I'm lost: How can I check if events are fired? I was looking for something like Assert.Raise or Assert.Fire but there's 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.

Thank you!

Answer

Dror Helper picture Dror Helper · Aug 2, 2010

Checking if events were fired 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 lambdas:

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

...

Assert.IsTrue(wasCalled);