countdown: add first mock for sleep
This commit is contained in:
		@ -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)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
				
			|||||||
@ -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)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user