|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +func TestCountdown(t *testing.T) { |
| 11 | + |
| 12 | + t.Run("prints 3 to Go!", func(t *testing.T) { |
| 13 | + buffer := &bytes.Buffer{} |
| 14 | + Countdown(buffer, &SpyCountdownOperations{}) |
| 15 | + |
| 16 | + got := buffer.String() |
| 17 | + want := `3 |
| 18 | +2 |
| 19 | +1 |
| 20 | +Go!` |
| 21 | + |
| 22 | + if got != want { |
| 23 | + t.Errorf("got %q want %q", got, want) |
| 24 | + } |
| 25 | + }) |
| 26 | + |
| 27 | + t.Run("sleep before every print", func(t *testing.T) { |
| 28 | + spySleepPrinter := &SpyCountdownOperations{} |
| 29 | + Countdown(spySleepPrinter, spySleepPrinter) |
| 30 | + |
| 31 | + want := []string{ |
| 32 | + write, |
| 33 | + sleep, |
| 34 | + write, |
| 35 | + sleep, |
| 36 | + write, |
| 37 | + sleep, |
| 38 | + write, |
| 39 | + } |
| 40 | + |
| 41 | + if !reflect.DeepEqual(want, spySleepPrinter.Calls) { |
| 42 | + t.Errorf("wanted calls %v got %v", want, spySleepPrinter.Calls) |
| 43 | + } |
| 44 | + }) |
| 45 | +} |
| 46 | + |
| 47 | +func TestConfigurableSleeper(t *testing.T) { |
| 48 | + sleepTime := 5 * time.Second |
| 49 | + |
| 50 | + spyTime := &SpyTime{} |
| 51 | + sleeper := ConfigurableSleeper{sleepTime, spyTime.Sleep} |
| 52 | + sleeper.Sleep() |
| 53 | + |
| 54 | + if spyTime.durationSlept != sleepTime { |
| 55 | + t.Errorf("should have slept for %v but slept for %v", sleepTime, spyTime.durationSlept) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +type SpyCountdownOperations struct { |
| 60 | + Calls []string |
| 61 | +} |
| 62 | + |
| 63 | +func (s *SpyCountdownOperations) Sleep() { |
| 64 | + s.Calls = append(s.Calls, sleep) |
| 65 | +} |
| 66 | + |
| 67 | +func (s *SpyCountdownOperations) Write(p []byte) (n int, err error) { |
| 68 | + s.Calls = append(s.Calls, write) |
| 69 | + return |
| 70 | +} |
| 71 | + |
| 72 | +const write = "write" |
| 73 | +const sleep = "sleep" |
| 74 | + |
| 75 | +type SpyTime struct { |
| 76 | + durationSlept time.Duration |
| 77 | +} |
| 78 | + |
| 79 | +func (s *SpyTime) Sleep(duration time.Duration) { |
| 80 | + s.durationSlept = duration |
| 81 | +} |
0 commit comments