Isolator trick – Unit Testing ThreadPool.QueueUserWorkItem()

Unit testing asynchronous stuff is tough. This is something I had to live with for the last few days working on one of our products. This is compounded by having to unit test jobs that go through ThreadPool.QueueUserWorkItem() – because it’s using the ThreadPool it’s hard to synchronize your test. If you just do this:

Your test will almost always succeed. But then again it just might fail – there’s a race condition between the assertion and the background thread on setInBackground. This is of course a hugely simplified case – usually the call to QueueUserWorkItem() is hidden somewhere in the code under test where it does time consuming calculations and not just setting boolean values. These race conditions may cause nastier results than a simple dirty bool, and may be quite hard to debug.

Now, it’s our responsibility to synchronize our tests – always make sure everything in the code under test finished running before asserting against it. But how does one synchronize the ThreadPool? We all know how to synchronize a Thread, right? Just .Join() on it and you’re good. How about we turn the mighty ThreadPool into a puny Thread using Isolator?

First, we need to refactor the call to ThreadPool.QueueUserWorkItem() to a method we can fake – unfortunately, we can’t fake it directly because it’s in mscorlib. Let’s say we did it like this:

Now, using DoInstead() we turn the call to QueueAsyncJob to a call to a Thread. This way we maintain the asynchronous nature of the code under test, and maintain the capability to synchronize our test without jumping through hoops. For instance:

Mission accomplished! Lets do a quick recap – we need to test code that uses ThreadPool.QueueUserWorkIteam(). This is not fun because we can’t easily wait for all worker threads to finish, and it’s hard to synchronize our tests that way. Solution – we switch from using ThreadPool to using a regular Thread! How? extract the call to ThreadPool into a method, and when that method is called, replace its implementation (using the wonderfully flexible DoInstead()) with a simple thread creation and invocation. Before you assert on the test’s result, just call Thread.Join() and you’re good!