Unit testing multi-threaded, asynchronous code and/or events
I've been writing some unit tests recently that test some multi-threaded functionality.
Typically this involves hooking up some event handlers then waiting for some asynchronous code to fire the event before proceeding with the unit test and assertions.
The ManualResetEvent class seems a good choice for this, and this post has a small example of using it in a unit test:
[Test()]
public void AfterRunAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
TestTestCase tc = new TestTestCase(1, "", 0, 0);
bool eventFired = false;
tc.RunCompleted +=
delegate(object sender, AsyncCompletedEventArgs e) {
Assert.IsInstanceOfType(typeof (TestTestCase), sender, "sender is TestCase");
bool passed = tc.Passed;
string output = tc.Output;
eventFired = true;
manualEvent.Set();
};
tc.RunAsync();
manualEvent.WaitOne(500, false);
Assert.IsTrue(eventFired, "RunCompleted fired");
}