Five approaches for making time-dependent C++ code unit-testable are compared. The naive approach of calling std::chrono::now() directly is untestable. Alternatives include alias clocks (requires separate builds), template specialization tricks (avoids separate builds), clock factories (singleton problems), injecting clocks via constructors, and passing timestamps as parameters. The recommended approach is passing timestamps directly to functions, which simplifies tests and avoids singletons, with template specialization as a fallback when precision loss is unacceptable.
Table of contents
Approach 1, the alias clock Copy link Link copied!Approach 2, template specialization access Copy link Link copied!Approach 3, the clock factory Copy link Link copied!Approach 4, clocks from above Copy link Link copied!Approach 5, pass time stamps Copy link Link copied!Which to choose? Copy link Link copied!Sort: