Hacker News new | ask | show | jobs
by JimmyAustin 905 days ago
The function you pass in can keep track of how many times it’s been called, and provide different values on each call.
1 comments

This is way way worse than passing in a timer and destroys your ability to write multi threaded code (among other defects).
This is for unit testing. Even if your unit tests run in parallel, each test case will have it's own mocked clock.

This is not even an experimental approach, the mocking of timers is literally one of the canonic examples of the advantages of dependency injection. I have written this exact code multiple times, on my own, or refactoring others people untestable code to this pattern to be able to test them. A couple of times the reason for the refactoring was specifically to demonstrate the existence of race conditions, to have a test case that has the race condition be deterministic so we could fix it and be sure of the fix working.