countdown: add first mock for sleep
This commit is contained in:
parent
d7840e9cb7
commit
56be76b275
@ -11,11 +11,22 @@ const (
|
||||
countdownStart = 3
|
||||
)
|
||||
|
||||
func Countdown(out io.Writer) {
|
||||
type Sleeper interface {
|
||||
Sleep()
|
||||
}
|
||||
|
||||
type DefaultSleeper struct{}
|
||||
|
||||
func (d *DefaultSleeper) Sleep() {
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
|
||||
func Countdown(out io.Writer, sleeper Sleeper) {
|
||||
// XXX: The sequence is not tested
|
||||
for i := countdownStart; i > 0; i-- {
|
||||
fmt.Fprintf(out, "%d\n", i)
|
||||
// This is difficult to test!
|
||||
time.Sleep(1 * time.Second)
|
||||
sleeper.Sleep()
|
||||
}
|
||||
fmt.Fprint(out, finalWord)
|
||||
}
|
||||
|
@ -5,10 +5,19 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
type SpySleeper struct {
|
||||
Calls int
|
||||
}
|
||||
|
||||
func (s *SpySleeper) Sleep() {
|
||||
s.Calls++
|
||||
}
|
||||
|
||||
func TestCountdown(t *testing.T) {
|
||||
buffer := &bytes.Buffer{}
|
||||
sleeper := &SpySleeper{}
|
||||
|
||||
Countdown(buffer)
|
||||
Countdown(buffer, sleeper)
|
||||
|
||||
got := buffer.String()
|
||||
want := `3
|
||||
@ -19,4 +28,8 @@ Go!`
|
||||
if got != want {
|
||||
t.Errorf("got %q want %q", got, want)
|
||||
}
|
||||
|
||||
if sleeper.Calls != 3 {
|
||||
t.Errorf("not enough calls to sleeper, want 3 got %d", sleeper.Calls)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user