If I have an subject under test with a timer that causes some action to be taken at a timed interval, what's a good way to test that?
One method is to wrap the timer in an interface and inject it as a dependency.
However, I'd like to avoid creating yet another abstraction. It seems I can avoid that by injecting the update interval rather than the timer. Then in my test (assuming the AAA style of testing), I put a Thread.Sleep
after Act and before Assert, using a very small time value so the test doesn't take long to run.
Is that a bad idea? I know it probably doesn't fully follow the principles of TDD, but it seems like there has to be a line where you stop surrounding everything with a contract and injecting it.
If the amount you sleep doesn't have any significance on the test and you can set i to 1 millisecond then is should be fine to simply sleep for 1 millisecond in your test.
However, if you want to test complex timing behavior with timeouts and specific actions being taken at specific points in time it quickly becomes easier to abstract the concept of time and inject it as a dependency. Then your tests can operate in virtual time and execute without delay even though the code operates as if real time was passing.
A simple way to virtualize time is to use something like this:
You will have to extend this idea if you require more reactive behavior like timers firing etc.