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!
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With