golangのTimer, Tickerのモック
time.Timer, time.Tickerを使ったコードのテストのために、それらをモックする以下のコードを書いた。 しかし、私が解決したい問題としては、tickerの時間を秒からミリ秒へ変えること。 そのため、MockTimerでも内部でtime.Tickerを保持しミリ秒で動くものとなる。 その場合、time.NewTicker にて指定するDurationを短くすれば解決する。 従って不要。 時間無駄にしたorz...
type Ticker interface {
Set(d *time.Duration)
C() <-chan time.Time
Stop()
Reset(d time.Duration)
}
type TickerDuration time.Duration
func NewRealTimer(d TickerDuration) *RealTicker {
return &RealTicker{tk: time.NewTicker(time.Duration(d))}
}
type RealTicker struct {
tk *time.Ticker
}
func (t *RealTicker) Set(d *time.Duration) {
t.tk = time.NewTicker(*d)
}
func (t *RealTicker) C() <-chan time.Time {
return t.tk.C
}
func (t *RealTicker) Stop() {
t.tk.Stop()
}
func (t *RealTicker) Reset(d time.Duration) {
t.tk.Reset(d)
}
func NewMockTimer(d TickerDuration) *MockTicker {
return &MockTicker{}
}
type MockTicker struct{}
func (t *MockTicker) C() <-chan time.Time {
}
func (t *MockTicker) Stop() {
}
func (t *MockTicker) Reset(d time.Duration) {
}