go-by-test/countdown/countdown_test.go

57 lines
993 B
Go
Raw Normal View History

2024-09-17 19:10:09 +00:00
package countdown
import (
"bytes"
2024-09-17 19:30:53 +00:00
"reflect"
2024-09-17 19:10:09 +00:00
"testing"
)
2024-09-17 19:30:53 +00:00
const (
write = "write"
sleep = "sleep"
)
type SpyCountdownOperations struct {
Calls []string
2024-09-17 19:20:33 +00:00
}
2024-09-17 19:30:53 +00:00
func (s *SpyCountdownOperations) Sleep() {
s.Calls = append(s.Calls, sleep)
2024-09-17 19:20:33 +00:00
}
2024-09-17 19:30:53 +00:00
func (s *SpyCountdownOperations) Write(p []byte) (n int, err error) {
s.Calls = append(s.Calls, write)
return 0, nil
}
2024-09-17 19:10:09 +00:00
2024-09-17 19:30:53 +00:00
func TestCountdown(t *testing.T) {
t.Run("print 3 to Go!", func(t *testing.T) {
buffer := &bytes.Buffer{}
Countdown(buffer, &SpyCountdownOperations{})
2024-09-17 19:10:09 +00:00
2024-09-17 19:30:53 +00:00
got := buffer.String()
want := `3
2024-09-17 19:10:09 +00:00
2
1
Go!`
2024-09-17 19:30:53 +00:00
if got != want {
t.Errorf("got %q want %q", got, want)
}
})
t.Run("sleep before every print", func(t *testing.T) {
spySleepPrinter := &SpyCountdownOperations{}
Countdown(spySleepPrinter, spySleepPrinter)
want := []string{
write, sleep, write, sleep, write, sleep, write,
}
2024-09-17 19:20:33 +00:00
2024-09-17 19:30:53 +00:00
if !reflect.DeepEqual(want, spySleepPrinter.Calls) {
t.Errorf("wanted %v got %v", want, spySleepPrinter.Calls)
}
})
2024-09-17 19:10:09 +00:00
}