Skip to content

Commit

Permalink
added v5 with sleeper tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hackeryarn committed May 20, 2018
1 parent 603857d commit 4daae70
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 0 deletions.
82 changes: 82 additions & 0 deletions mocking/v5/countdown_test.go
@@ -0,0 +1,82 @@
package main

import (
"bytes"
"reflect"
"testing"
"time"
)

func TestCountdown(t *testing.T) {

t.Run("prints 5 to Go!", func(t *testing.T) {
buffer := &bytes.Buffer{}
Countdown(buffer, &CountdownOperationsSpy{})

got := buffer.String()
want := `3
2
1
Go!`

if got != want {
t.Errorf("got '%s' want '%s'", got, want)
}
})

t.Run("sleep after every print", func(t *testing.T) {
spySleepPrinter := &CountdownOperationsSpy{}
Countdown(spySleepPrinter, spySleepPrinter)

want := []string{
sleep,
write,
sleep,
write,
sleep,
write,
sleep,
write,
}

if !reflect.DeepEqual(want, spySleepPrinter.Calls) {
t.Errorf("wanted calls %v got %v", want, spySleepPrinter.Calls)
}
})
}

func TestConfigurableSleeper(t *testing.T) {
sleepTime := 5 * time.Second

spyTime := &SpyTime{}
sleeper := ConfigurableSleeper{sleepTime, spyTime.Sleep}
sleeper.Sleep()

if spyTime.durationSlept != sleepTime {
t.Errorf("should have slept for %v but slept for %v", sleepTime, spyTime.durationSlept)
}
}

type CountdownOperationsSpy struct {
Calls []string
}

func (s *CountdownOperationsSpy) Sleep() {
s.Calls = append(s.Calls, sleep)
}

func (s *CountdownOperationsSpy) Write(p []byte) (n int, err error) {
s.Calls = append(s.Calls, write)
return
}

const write = "write"
const sleep = "sleep"

type SpyTime struct {
durationSlept time.Duration
}

func (s *SpyTime) Sleep(duration time.Duration) {
s.durationSlept = duration
}
44 changes: 44 additions & 0 deletions mocking/v5/main.go
@@ -0,0 +1,44 @@
package main

import (
"fmt"
"io"
"os"
"time"
)

// Sleeper allows you to put delays
type Sleeper interface {
Sleep()
}

// ConfigurableSleeper is an implementation of Sleeper with a defined delay
type ConfigurableSleeper struct {
duration time.Duration
sleep func(time.Duration)
}

// Sleep will pause execution for the defined Duration
func (c *ConfigurableSleeper) Sleep() {
c.sleep(c.duration)
}

const finalWord = "Go!"
const countdownStart = 3

// Countdown prints a countdown from 5 to out with a delay between count provided by Sleeper
func Countdown(out io.Writer, sleeper Sleeper) {

for i := countdownStart; i > 0; i-- {
sleeper.Sleep()
fmt.Fprintln(out, i)
}

sleeper.Sleep()
fmt.Fprint(out, finalWord)
}

func main() {
sleeper := &ConfigurableSleeper{1 * time.Second, time.Sleep}
Countdown(os.Stdout, sleeper)
}

0 comments on commit 4daae70

Please sign in to comment.