I’ve got a class that has a private member that has for type System.Windows.Forms.Timer. There’s also a private method that is being called every time my timer ticks.
- Is it worth testing the method? (since it’s private)
- How can I test it? (I know I can have my test class inheriting the class I want to test…)
- Should I be mocking my timer? Because if I have to test a class that uses an internal timer, my tests may take a lot of time to complete, right?
edit:
Actually, the method has a dependency on timing, here’s the code:
private void alertTick(object sender, EventArgs e) {
if (getRemainingTime().Seconds <= 0) {
Display.execute(Name, WarningState.Ending, null);
AlertTimer.Stop();
}
else {
var warning = _warnings.First(x => x == getRemainingTime());
if (warning.TotalSeconds > 0)
Display.execute(Name, WarningState.Running, warning);
}
}
As you can see, if the timer is running, it calls Display.execute() with different parameters from when it’s ending (when the remaining time equals 0). Would that be a problem of design?
Actually your class have too many responsibilities – one is scheduling some task, and another – executing some actions. Try to split your class into two separate classes with single responsibilities.
So, scheduling goes to scheduler 🙂 API of scheduler could be like:
Forget about scheduler for now. Return and implement your second class, which will display some warnings. Let’s go test first (with Moq):
Write implementation:
Test passes. Write another one:
Test failed. Ah, you need condition for remaining time:
You can continue writing tests for your class, which responsible for handling scheduler alerts and executing some warnings on display. When you finish, you can write implementation for your
ISchedulerinterface. It does not matter how you will implement scheduling – via System.Windows.Forms.Timer or via System.ThreadingTimer, or some other way.