this repo has no description

:sparkles: (Go) mocking

Changed files
+109
Go
+36
Go/mocking/mocking.go
··· 1 + package main 2 + 3 + import ( 4 + "fmt" 5 + "io" 6 + "os" 7 + "time" 8 + ) 9 + 10 + type Sleeper interface { 11 + Sleep() 12 + } 13 + 14 + const ( 15 + finalWord = "Go!" 16 + countdownStart = 3 17 + ) 18 + 19 + func Countdown(out io.Writer, sleeper Sleeper) { 20 + for i := countdownStart; i > 0; i-- { 21 + fmt.Fprintln(out, i) 22 + sleeper.Sleep() 23 + } 24 + fmt.Fprint(out, finalWord) 25 + } 26 + 27 + type DefaultSleeper struct {} 28 + 29 + func (d *DefaultSleeper) Sleep() { 30 + time.Sleep(1 * time.Second) 31 + } 32 + 33 + func main() { 34 + sleeper := &DefaultSleeper{} 35 + Countdown(os.Stdout, sleeper) 36 + }
+73
Go/mocking/mocking_test.go
··· 1 + package main 2 + 3 + import ( 4 + "bytes" 5 + "reflect" 6 + "testing" 7 + ) 8 + 9 + type SpySleeper struct { 10 + Calls int 11 + } 12 + 13 + func (s *SpySleeper) Sleep() { 14 + s.Calls++ 15 + } 16 + 17 + type SpyCountdownOperations struct { 18 + Calls []string 19 + } 20 + 21 + func (s *SpyCountdownOperations) Sleep() { 22 + s.Calls = append(s.Calls, sleep) 23 + } 24 + 25 + func (s *SpyCountdownOperations) Write(p []byte) (n int, err error) { 26 + s.Calls = append(s.Calls, write) 27 + return 28 + } 29 + 30 + const write = "write" 31 + const sleep = "sleep" 32 + 33 + func TestCountdown(t *testing.T) { 34 + t.Run("spying sleep", func(t *testing.T) { 35 + buffer := &bytes.Buffer{} 36 + spySleeper := &SpySleeper{} 37 + 38 + Countdown(buffer, spySleeper) 39 + 40 + got := buffer.String() 41 + want := `3 42 + 2 43 + 1 44 + Go!` 45 + 46 + if got != want { 47 + t.Errorf("got %q want %q", got, want) 48 + } 49 + 50 + if spySleeper.Calls != 3 { 51 + t.Errorf("not enough calls to sleeper, want 3 got %d", spySleeper.Calls) 52 + } 53 + }) 54 + 55 + t.Run("sleep before every print", func(t *testing.T) { 56 + spySleepPrinter := &SpyCountdownOperations{} 57 + Countdown(spySleepPrinter, spySleepPrinter) 58 + 59 + want := []string{ 60 + write, 61 + sleep, 62 + write, 63 + sleep, 64 + write, 65 + sleep, 66 + write, 67 + } 68 + 69 + if !reflect.DeepEqual(want, spySleepPrinter.Calls) { 70 + t.Errorf("wanted calls %v got %v", want, spySleepPrinter.Calls) 71 + } 72 + }) 73 + }