Re:Mocking time and testing event loops in Go
by dimonomid on Monday May 25, 2020 @10:17AM
(#23301356)
The yet another external dependency is way more than Now() though. Mocking just Now() is trivial, but most of the time it's by far not the only function which I personally use from the time package.
Re:Mocking time and testing event loops in Go
by jonathanoliver on Monday May 25, 2020 @10:46AM
(#23301603)
Correct. In my use case, I just need a simple replacement for time.Now(). If I needed more (time.After, for example), there's a point that bringing in an external dependency makes sense.
1. Pass in a value called `now func() time.Time` into the constructor function of my struct. This allows me to call `inst.now()` on a particular instance of my structure.
2. Have a global field in a package: `var Now func() time.Time = time.Now` This allows `mypkg.Now()`
All of this avoids taking yet another external package dependency with only a couple of lines of code.