In C#, If you need to unit test a class that fires an event in certain circumstances (perhaps even asynchronously), you need to handle a little more than just running some code and doing the assertion. You have to make sure your unit test waits for the event to be fired. Here’s one naive way of doing it, a WRONG way:
There are a number of things wrong with this:
- The class variables. More complex unit test class. Have to coordinate these variables across multiple functions.
- Since they are class variables, you will want to reuse them, but you’d better remember to reset the event and the boolean every time!
- Have to have two functions to do something really, really simple.
- The WaitOne() does not have a timeout, so if the wait is ever satisfied then statsUpdated is guaranteed to be true.
Here’s a better way of doing it, using anonymous methods in C# 2.0:
- The event is just part of the method. Since the event handler is an anonymous delegate, it can access the enclosing method’s local variables.
- Added 5,000ms timeout to the WaitOne() function to prevent hanging of unit tests.