Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test events with nunit

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!

like image 984
atamanroman Avatar asked Aug 02 '10 11:08

atamanroman


2 Answers

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); 
like image 82
Dror Helper Avatar answered Sep 28 '22 01:09

Dror Helper


I prefer to do as follows:

var wait = new AutoResetEvent(false); foo.MeEvent += (sender, eventArgs) => { wait.Set(); }; Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(5))); 

Advantages: Supports multithreading scenario (if handler is invoked in different thread)

like image 23
aderesh Avatar answered Sep 28 '22 03:09

aderesh