The method I use to create testable time-dependent code is to ask for a “clock”. A clock is a provider for the progression of time, an instance of an interface with methods for all the various time-related things the code might want to do: delaying an action, measuring elapsed time, creating periodic events, querying the date, whatever you need.
When the code is being run in production, the provided clock will be advancing with respect to external time. When the code is being tested, the provided clock will be a “fake” manually controlled instanced that the test can advance as needed.
Interestingly, once you’re asking for clocks everywhere, you can start reaping some benefits unrelated to testing.
Stay up-to-date by subscribing to the Comments RSS Feed for this post.