/
01_loader.go
72 lines (57 loc) · 1.38 KB
/
01_loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package unit_tests
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
"github.com/stretchr/testify/assert"
)
type Loader interface {
Load(ID int) (*Pet, error)
}
func TestLoadAndPrint_happyPath(t *testing.T) {
result := &bytes.Buffer{}
LoadAndPrint(&happyPathLoader{}, 1, result)
assert.Contains(t, result.String(), "Pet named")
}
func TestLoadAndPrint_notFound(t *testing.T) {
result := &bytes.Buffer{}
LoadAndPrint(&missingLoader{}, 1, result)
assert.Contains(t, result.String(), "no such pet")
}
func TestLoadAndPrint_error(t *testing.T) {
result := &bytes.Buffer{}
LoadAndPrint(&errorLoader{}, 1, result)
assert.Contains(t, result.String(), "failed to load")
}
func LoadAndPrint(loader Loader, ID int, dest io.Writer) {
loadedPet, err := loader.Load(ID)
if err != nil {
fmt.Fprintf(dest, "failed to load pet with ID %d with error: %s", ID, err)
return
}
if loadedPet == nil {
fmt.Fprintf(dest, "no such pet found")
return
}
fmt.Fprintf(dest, "Pet named %s loaded", loadedPet.Name)
}
// implements Loader
type happyPathLoader struct {
}
func (l *happyPathLoader) Load(ID int) (*Pet, error) {
return &Pet{}, nil
}
// implements Loader
type missingLoader struct {
}
func (l *missingLoader) Load(ID int) (*Pet, error) {
return nil, nil
}
// implements Loader
type errorLoader struct {
}
func (l *errorLoader) Load(ID int) (*Pet, error) {
return nil, errors.New("failed")
}