update
This commit is contained in:
parent
96a19ac142
commit
0586ce15a0
42
mocking/countdown.go
Normal file
42
mocking/countdown.go
Normal 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
27
mocking/countdown_test.go
Normal 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)
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user