On Fri, Jul 30, 2021 at 12:13 AM Carl <carle...@gmail.com> wrote:

> Hi,
>
> Is there a way to write a unit test that simulates a change in the wall
> clock for a time.Time value?
>

I use a combination of two approaches to simulate the passage of time
(often both work together):

   - have functions a `now` argument so the caller supplies the timestamp
   (this avoids timestamp-skew for cases where the timestamps should be close
   together anyway)
   - Use a package like https://github.com/vimeo/go-clocks (
   https://pkg.go.dev/github.com/vimeo/go-clocks) to use a real clock in
   production, but have a fake clock you can advance/set however you want
   without impinging on the main code

Full disclosure: I wrote github.com/vimeo/go-clocks, so I might be a bit
biased -- it is based on one of Google's internal packages for C++, though.

One additional benefit of using a fake clock is that it allows for
fine-grained synchronization between tests and code if you're sleeping in
goroutines, as the fake clock in go-clocks has methods for awaiting a
certain number of sleepers, etc.


>
> Cheers,
> Carl
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/f306417d-46f9-4ccd-8e7c-69a1dbd14969n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/f306417d-46f9-4ccd-8e7c-69a1dbd14969n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANrC0Bj6KMLQ-erdAB0dfJC1XSNw%2BgWfx43pqSAZ8W4efpnZQQ%40mail.gmail.com.

Reply via email to