Unit testing multi threaded code–Timers

No comments

Tuesday, March 26, 2013

Writing unit tests for multi-threaded is not simple and could even be impossible for some scenarios – how could you test that an asynchronous method was not called?
Since most unit testing examples tend to be rather trivial I’ve decided to try and explain other more complex scenarios – preferably without using any calculator examples.

The “Timer” problem

Consider the Timer class (or rather classes), .NET has several classes called Timer, In this post I’m referring to System.Threading.Timer and System.Timers.Timer which is built on top of the former.
Both perform an action in another thread (using the Thread Pool) in intervals (not accurately – but I won’t go there in this post).
Consider the following class:
public class ClassUnderTest
    private readonly Timer _timer;

    public ClassUnderTest()
        _timer = new Timer(1000);
        _timer.Elapsed += PerformPeriodicAction;

    public ClassUnderTest(Timer timer)
        _timer = timer;
        _timer.Elapsed += PerformPeriodicAction;

    private void PerformPeriodicAction(object sender, ElapsedEventArgs e)
        // Perform very important task here!
Testing code that employs timers can be tricky. Unfortunately there’s a tendency to write a test that looks like this when timers are involved:
public void TestJustWrong()
    var cut = new ClassUnderTest();

    // Make sure the timer executed at least once

    // Check that something happens

So what is the problem?

Although it might seem like a valid unit test – in fact it’s a test that would fail from time to time - whenever the timer would happen to “tick” for more than the sleep period.
These kind of tests are known as the “the test that tends to fail” and usually “fixed” by running the build script another time.
You do not want a test that you cannot trust to fail only when a bug is introduced into your system.
Sadly I’ve seen this code – a lot! But no more - writing a good unit test for that class is simple, in fact there is more than one alternative that creates a simple, trustworthy unit test.

Solution 1 – invoke the handler instead

Instead of waiting for the time to execute why not call the method that handles the timer’s event?
First we need to make sure that the method we’re going to call is internal or public. I personally don’t like changing my production code that much in order to make the code “testable” but it’s a way.
Now all we have to do is call the method thus making sure that execution happens exactly when we want it – and a unit test is born:
public void TestByMethod()
    var cut = new ClassUnderTestForTestability();

    // Let's call the method
    cut.PerformPeriodicAction(this, null);

    // Check that something happens

Solution 2 – invoke the timer at your leisure

Most modern Isolation (a.k.a Mocking) frameworks have the ability to invoke events as well as create fake objects.
We’re going to create a fake timer and invoke the elapsed event. Using simple constructor injection we’ll pass the timer to our class under test prior to invocation and we have a more robust unit test:
public void TestWithFakeTimer()
    var fakeTimer = Isolate.Fake.Instance<Timer>();

    var cut = new ClassUnderTest(fakeTimer);

    // Let's invoke the event
    Isolate.Invoke.Event(() => fakeTimer.Elapsed += null, this, null);

    // Check that something happens
I’m using Typemock Isolator but you can use the isolation framework of your choice The syntax is strange but once you’ll get used to it, it’s simple.
The added value is that we’re causing the real flow of our program to execute – in a synchronized and timely manner.


Although there are many ways to test code that uses timers I find myself employing the two above most of the time.
I plan to write a few more posts on the other pitfall of testing multi-threaded code (and how to avoid them) but until then –

happy coding…

Spreading the agile joy

1 comment

Friday, March 01, 2013

I finally hit critical mass!

I got a request from one of the project managers (not my project) to do a quick “introduction to Scrum” session.

It took quite a while – more than two years (and a downsizing) in order for other teams to notice that we have a different way to do things.

I did a very successful session – mainly because the audience “felt the pain”; it was fun explaining about Scrum with examples on how they can utilize it the very next day.

Since I’m not in daily contact with that team – I had no idea how well they implemented Scrum. Until yesterday when I walked on a meeting that had a task board on a big screen – so I guess it went well.

When I was first asked to do this session I wanted to create a simple and short presentation that can be re-used – And here it is:


It’s simple and short so I use it as a “background” for a discussion on how they are going to use Scrum in their work – today.


I guess I’m doing something right since I have another session next week!


And if you have an agile success story – please share…

Related Posts Plugin for WordPress, Blogger...