Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test classes that use timers internally?

Like it or not, occasionally you have have to write tests for classes that make internal use of timers.

Say for example a class that takes reports of system availability and raises an event if the system has been down for too long

public class SystemAvailabilityMonitor {
    public event Action SystemBecameUnavailable = delegate { };
    public event Action SystemBecameAvailable = delegate { };
    public void SystemUnavailable() {
        //..
    }
    public void SystemAvailable() {
        //..
    }
    public SystemAvailabilityMonitor(TimeSpan bufferBeforeRaisingEvent) {
        //..
    }
}

I have a couple tricks which I use (will post these as an answer) but I wonder what other people do since I'm not fully satisfied with either of my approaches.

like image 584
George Mauer Avatar asked May 18 '09 21:05

George Mauer


1 Answers

I extract the timer from the object that reacts to the alarm. In Java you can pass it a ScheduledExecutorService, for example. In unit tests I pass it an implementation that I can control deterministically, such as jMock's DeterministicScheduler.

like image 133
Nat Avatar answered Sep 25 '22 03:09

Nat