Unit testing threading using rhino mocks

Update: I have recently put together a much more detailed look at this in my obstacles of unit testing series https://journalofasoftwaredev.wordpress.com/2009/05/02/obstacles-of-unit-testing-methods-to-side-step-them-part-2-multi-threading/

I recently had to do some unit testing against my TaskScheduler class this presented a problem… the TaskScheduler performs it’s monitoring by spawning a worker thread in the background so I needed a way to test this asynchronous behaviour. Thanks to the excellent Rhino Mocks and using the ManualResetEvent I come up with the following solution:

public void Should_run_scheduled_task_when_datetime_met()
	ManualResetEvent evt = new ManualResetEvent(false);
	DateTime runAt = new DateTime(2008, 1, 1, 12, 0, 0);
	ITask mockTask = mocks.DynamicMock();
	ITaskRunner mockTaskRunner = mocks.DynamicMock();

	using (mocks.Record())


		LastCall.On(mockTaskRunner).Do(new TaskRunnerRunDelegate(delegate(ITask task)

	using (mocks.Playback())
		ITaskScheduler sut = createSUT(new MockDateTimeSource(runAt.AddSeconds(-2)), mockTaskRunner);
   	        evt.WaitOne(4000, false);

When a Task that the TaskScheduler is monitoring reaches its scheduled execution date/time the TaskScheduler Hands off to an ITaskRunner in this case it’s a mocked out interface, we can use this to listen out for a call to the Run method, and set the ManualResetEvent thus exiting the WaitOne block. The downside to this approach is establishing what the timeout should be in most cases this will be a few seconds.


2 thoughts on “Unit testing threading using rhino mocks

  1. I really Feel article, “Unit testing threading using rhino mocks
    Journal of a software dev” ended up being spot on!
    Icannot agree together with you more! Finally looks like Icame across a blog website
    worth browsing. Thanks for the post, Ricky

Comments are closed.