Search code examples
c#unit-testingeventsnunitc#-2.0

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!


Solution

  • 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);