4 ms·
There are two ways I've done this. 1. Pass in a value called `now func() time.Time` into the constructor function of my struct. This allows me to call `inst.no
by jonathanoliver 6y ago
There are two ways I've done this.
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.
- dimonomid 6y agoThe 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.
- jonathanoliver 6y agoCorrect. 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.