Re:Mocking time and testing event loops in Go
by jrockway on Monday May 25, 2020 @12:33PM
(#23302585)
There is nothing deep going on here. People inject fake clocks so they can write a test like assertRow(got, row{creationTime: time.Date(2020, 5, 25, 0, 0, 0, 0)}) and have the test always pass. (Or cases like "on Sunday, do X" and you want your unit tests to work on Sunday as well as other days.) Additionally, you sometimes want shorter timeouts against your fake backend, so that when you make an error it takes milliseconds for your test to fail instead of the longer amount of time you'd prefer in production.
You don't have to use globals for any of this, but people like doing it, and then have a bunch of workarounds to make the tests work. If you don't want workarounds, your API can be "func CreateRow(..., now time.Time)" or "func DoSomethingWithTimeout(timeout time.Duration)" and just pass the correct values in. (Don't do the timeout one, though, just use a context.)
You don't have to use globals for any of this, but people like doing it, and then have a bunch of workarounds to make the tests work. If you don't want workarounds, your API can be "func CreateRow(..., now time.Time)" or "func DoSomethingWithTimeout(timeout time.Duration)" and just pass the correct values in. (Don't do the timeout one, though, just use a context.)