countdown: add first mock for sleep

This commit is contained in:
vinchent 2024-09-17 21:20:33 +02:00
parent d7840e9cb7
commit 56be76b275
3 changed files with 28 additions and 4 deletions

View File

@ -11,11 +11,22 @@ const (
countdownStart = 3 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-- { for i := countdownStart; i > 0; i-- {
fmt.Fprintf(out, "%d\n", i) fmt.Fprintf(out, "%d\n", i)
// This is difficult to test! // This is difficult to test!
time.Sleep(1 * time.Second) sleeper.Sleep()
} }
fmt.Fprint(out, finalWord) fmt.Fprint(out, finalWord)
} }

View File

@ -5,10 +5,19 @@ import (
"testing" "testing"
) )
type SpySleeper struct {
Calls int
}
func (s *SpySleeper) Sleep() {
s.Calls++
}
func TestCountdown(t *testing.T) { func TestCountdown(t *testing.T) {
buffer := &bytes.Buffer{} buffer := &bytes.Buffer{}
sleeper := &SpySleeper{}
Countdown(buffer) Countdown(buffer, sleeper)
got := buffer.String() got := buffer.String()
want := `3 want := `3
@ -19,4 +28,8 @@ Go!`
if got != want { if got != want {
t.Errorf("got %q want %q", 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)
}
} }

View File

@ -8,5 +8,5 @@ import (
func main() { func main() {
// greet.Greet(os.Stdout, "Elodie") // greet.Greet(os.Stdout, "Elodie")
countdown.Countdown(os.Stdout) countdown.Countdown(os.Stdout, &countdown.DefaultSleeper{})
} }