This commit is contained in:
Michael Thomson 2024-05-31 11:32:55 -04:00
parent 96a19ac142
commit 0586ce15a0
No known key found for this signature in database
2 changed files with 69 additions and 0 deletions

42
mocking/countdown.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"fmt"
"io"
"os"
"time"
)
type Sleeper interface {
Sleep()
}
type SpySleeper struct {
Calls int
}
func (s *SpySleeper) Sleep() {
s.Calls++
}
type DefaultSleeper struct{}
func (d *DefaultSleeper) Sleep() {
time.Sleep(1 * time.Second)
}
const finalWord = "Go!"
const countdownStart = 3
func Countdown(out io.Writer, sleeper Sleeper) {
for i := countdownStart; i > 0; i-- {
fmt.Fprintln(out, i)
sleeper.Sleep()
}
fmt.Fprint(out, finalWord)
}
func main() {
sleeper := &DefaultSleeper{}
Countdown(os.Stdout, sleeper)
}

27
mocking/countdown_test.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"bytes"
"testing"
)
func TestCountdown(t *testing.T) {
buffer := &bytes.Buffer{}
spySleeper := &SpySleeper{}
Countdown(buffer, spySleeper)
got := buffer.String()
want := `3
2
1
Go!`
if got != want {
t.Errorf("got %q want %q", got, want)
}
if spySleeper.Calls != 3 {
t.Errorf("not enough calls to sleeper, want 3 got %d", spySleeper.Calls)
}
}