Created
June 8, 2018 00:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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