Skip to content

Instantly share code, notes, and snippets.

@tsuna
Created June 8, 2018 00:25
Show Gist options
  • Save tsuna/5cd39f087a16b75e545104ecc92893f7 to your computer and use it in GitHub Desktop.
Save tsuna/5cd39f087a16b75e545104ecc92893f7 to your computer and use it in GitHub Desktop.
Testing code with timers in Go in a 100% deterministic manner, without relying on time passing
package main
import (
"fmt"
"time"
)
type Foo struct {
t *time.Ticker
}
func NewFoo() *Foo {
return &Foo{
t: time.NewTicker(time.Second),
}
}
func (f *Foo) Run() {
for range f.t.C {
fmt.Println("tick!")
}
}
package main
import (
"testing"
"time"
)
func TestFooOnce(t *testing.T) {
f := NewFoo()
myticker := make(chan time.Time, 1)
// the "C" attribute is a receive-only chan so we need to use a local
// variable as the writing end.
f.t.C = myticker
myticker <- time.Time{}
close(myticker)
f.Run()
}
func TestFooTwice(t *testing.T) {
f := NewFoo()
myticker := make(chan time.Time, 2)
f.t.C = myticker
myticker <- time.Time{}
myticker <- time.Time{}
close(myticker)
f.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment