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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With