4 ms·
I initially played with passing an instance of a mockable time thing around everywhere that needed time, but it felt over the top to be passing around so many t
by rowanseymour 6y ago
I initially played with passing an instance of a mockable time thing around everywhere that needed time, but it felt over the top to be passing around so many things, solely for purposes of testing. So now it's just a thing you mock at a global level, e.g.
defer dates.SetNowSource(dates.DefaultNowSource)
dates.SetNowSource(dates.NewSequentialNowSource(time.Date(2018, 10, 18, 14, 20, 30, 123456, time.UTC)))
dates.Now()
- physicles 6y agoI've done this too, because passing a mockable time everywhere would just clutter the code, and this is an instance where a package-level global isn't going to bite you in the ass -- in prod anyway (in tests you might get your wires crossed, but seen another way, a global ensures all parts of your program think it's the same time). Difference in mine is that dates.SetNowSource returns a reset function that you can defer, like with context.WithCancel().