package ticker import ( "github.com/stretchr/testify/assert" "testing" "time" ) func TestTicker(t *testing.T) { now := time.Now() var data, expected []int64 // 预期每隔一秒收到一个信号 for i := 0; i < 3; i++ { expected = append(expected, now.Add(time.Duration(i)*time.Second).Unix()) } done := make(chan struct{}) ticker := NewTicker(time.Second) ticker.Start() go func() { for { select { case <-done: return case t := <-ticker.C: data = append(data, t.Unix()) } } }() go func() { // 设置成3秒有时候会有误差 time.Sleep(2500 * time.Millisecond) ticker.Stop() close(done) }() time.Sleep(3 * time.Second) assert.Equal(t, expected, data) }