clock
Small timer-driven library for mocking time in Go. Clockwork drop in replacement.
Why another one time mocking library?
- Race free
- Full featured
- Redesigned
Example
Suppose we have some type with time-dependent method that we wanna test.
Instead of direct use time
package we specify the clock field:
const incrementStateDelay = time.Hour
type myType struct {
clock clock.Clock
state int
}
func (f *myType) incrementState() {
f.clock.Sleep(incrementStateDelay)
f.state++
}
Now in tests we just inject FakeClock to the tested struct.
This allows us to manipulate time:
func TestExample(t *testing.T) {
fakeClock := clock.NewFakeClock()
mt := myType{clock: fakeClock}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
mt.incrementState()
wg.Done()
}()
fakeClock.BlockUntil(1)
if mt.state != 0 {
t.Fatalf("Unxepected state, expected=0 actual=%d", mt.state)
}
fakeClock.Advance(incrementStateDelay)
wg.Wait()
if mt.state != 1 {
t.Fatalf("Unxepected state, expected=1 actual=%d", mt.state)
}
}
In production simply inject the real clock instead
mt := myType{clock: clock.NewRealClock()}
Inspired by: