Unit Testing Events (The SpinWait.SpinUntil Method)

March 13, 2011 | Unit Testing | Async

The SpinWait.SpinUntil method spins until a specified condition is satisfied. This greatly improves the unit testing of events.

Let’s see first, how we test an event using hybrid thread synchronization constructs:

[Fact]
public void FooEvent()
{
    bool raised = false;
    ManualResetEventSlim done = new ManualResetEventSlim(false);
    ThreadPool.QueueUserWorkItem(delegate
    {
        Foo += new EventHandler<FooEventArgs>(
            (sender, e) => { raised = true; done.Set(); });
        RaiseFoo();
    }, null);
    done.Wait();
    Assert.True(raised);
}

Here is how the above test looks like when using the SpinWait.SpinUntil method:

[Fact]
public void FooEvent()
{
    bool raised = false;
    ThreadPool.QueueUserWorkItem(delegate
    {
        Foo += new EventHandler<FooEventArgs>(
            (sender, e) => { raised = true; });
        RaiseFoo();
    }, null);
    SpinWait.SpinUntil(() => raised == true);
    Assert.True(raised);
}

The above tests are exactly the same. The one with the SpinWait.SpinUntil method is easier to read and it also requires less code. Pretty cool.