Testing Time-Dependent Code with a Fake Clock
A fake clock supplies controlled times to a routine so a test can cross a deadline without sleeping or changing the system time.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
State the time sequence
For a ten-second timeout, supply an initial time of 100 and then 109 and 110 in seconds. Verify what happens before and at the deadline. Provide that clock through a dependency argument.
Keep the clock meaning consistent
Elapsed time needs a clock whose differences give elapsed duration. Calendar policies need a local date or time-zone-aware instant. A fake supplying elapsed values should use the same units as the production clock interface.[1]
Check just before and at an expiry boundary
A cache entry expires at five seconds after a fixed starting instant. Advance a fake clock to 4.999 seconds and observe a hit. Advance it to 5.000 seconds and expect expiry if the rule is inclusive. This takes no real waiting. See dependency arguments.
Fake time 0.000: put record
Fake time 4.999: read hit
Fake time 5.000: read miss under the stated contract
Give the substitute the same time model as production
Use an elapsed-time fake when the implementation uses a monotonic clock. For calendar deadlines, use explicit instants and time zones. Test the boundary and verify the clock is consulted through the expected adapter.