Unit Testing Multi-Threaded Asynchronous Events

I recently developed a stress/load testing tool. One of the classes implemented the Event-based Asynchronous Pattern. A good unit test for this class would be that the event is raised when expected (or at all). I found some posts on how to test events using NUnit. However, I did not see anything directly addressing the multi-threaded asynch event pattern. The following unit test uses an anonymous method and the ManualResetEvent to verify that the RunCompleted event fires after the call to RunAsync.

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.WaitOne(500, false);
    Assert.IsTrue(eventFired, "RunCompleted fired");

4 Responses to “Unit Testing Multi-Threaded Asynchronous Events”

  1. Chris Says:

    Thanks, this really helped me out… I knew it had to be possible, but wasn’t connecting the dots ’til I read this.

  2. Andrew Dedman Says:

    Thanks very much John, This was very useful.

  3. Unit testing multi-threaded, asynchronous code and/or events | David's Blog Says:

    […] ManualResetEvent class (MSDN) seems a good choice for this, and this post has a small example of using it in a unit test: [Test()] public void AfterRunAsync() { […]

  4. Sheik Mohamed Says:

    Really excellent . its work for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: