Testing when using the Task Parallel Library (TPL)

1 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 1 LinkedIn 0 1 Flares ×

I’ve been using the TPL on a project recently and have had to unit test the resulting methods. The implementation has been using WPF and MVVM, although I believe this method could be used for anything. What I ended up doing was largely influenced by this article, with some minor changes.

I will however, qualify that this technique wont work for testing everything – but it does no what I needed!

Setting Up the Scene

My example class is contrived but should represent what’s needed:

Here I have a simple situation where I make a call to a long running process (GetAllPeople), then this is processed back on to the main thread using the current synchronization context.

The problems arise in 2 parts – firstly, if you try to unit test this, the call to TaskScheduler.FromCurrentSynchronizationContext will throw an exception. Secondly, as the first part of the TPL call (to GetAllPeople) is executed asynchronously, your method may exit before the second part of the TPL call (to ProcessResults) has completed.

Custom Task Scheduler and ManualResetEvent

The solution I have used consists of creating a custom TaskScheduler with a NotifyCompleted event:

This scheduler only exists within my test assemblies, and is used purely for the purpose of forcing a certain behaviour. Notice that I directly invoke the callback and fire my notifycompleted event after it.

Then I construct my test like this:

The most important thing to note here is that I create a ManualResetEvent which effectively forces a wait before the assertions are made, until the test sync context signals that processing has completed.

This solution is not perfect and will need adjusting depending on circumstances (i.e. maybe you have more calls and need to to some counting or something) – it is probably also a good idea to timeout the manual reset event after a period of time.

,

The Essential App Marketing Kit
Subscribe To My Newsletter To Get an Entire Chapter From The Book for FREE
Never display this again
1 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 1 LinkedIn 0 1 Flares ×