I am currently writing a simple, timer based mini app in C# that performs an action n times every k seconds.
I am trying to adopt a test driven development style, so my goal is to unit test all parts of the app.
So, my question is: Is there a good way to unit test a timer based class?
The problem, as I see it, is that there is a big risk that the tests will take uncomfortably long to execute, since they must wait so and so long for the desired actions to happen.
Especially if one wants realistic data (seconds), instead of using the minimal time resolution allowed by the framework (1 ms?).
I am using a mock object for the action, to register the number of times the action was called, and so that the action takes practically no time.
An example of a real-world scenario that could be covered by a unit test is a checking that your car door can be unlocked, where you test that the door is unlocked using your car key, but it is not unlocked using your house key, garage door remote, or your neighbour's (who happen to have the same car as you) key.
Following are the most commonly used tools of unit testing: NUnit. JUnit. TestNG.
What I have done is to mock the timer, and also the current system time, that my events could be triggered immediately, but as far as the code under test was concerned time elapsed was seconds.
Len Holgate has a series of 20 articles on testing timer based code.
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