-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbird_handlers_test.go
97 lines (76 loc) · 2.31 KB
/
bird_handlers_test.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
)
func TestGetBirdsHandler(t *testing.T) {
// Initialize the mock store
mockStore := InitMockstore()
/* Define the data that we want to return when the mocks `GetBirds` method is
called
Also, we expect it to be called only once
*/
mockStore.On("GetBirds").Return([]*Bird{
{"sparrow", "A small harmless bird"},
}, nil).Once()
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(getBirdHandler)
// Now, when the handler is called, it should cal our mock store, instead of
// the actual one
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Bird{"sparrow", "A small harmless bird"}
b := []Bird{}
err = json.NewDecoder(recorder.Body).Decode(&b)
if err != nil {
t.Fatal(err)
}
actual := b[0]
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
// the expectations that we defined in the `On` method are asserted here
mockStore.AssertExpectations(t)
}
func TestCreateBirdsHandler(t *testing.T) {
mockStore := InitMockstore()
/*
Similarly, we define our expectations for th `CreateBird` method.
We expect the first argument to the method to be the bird struct
defined below, and tell the mock to return a `nil` error
*/
mockStore.On("CreateBird", &Bird{"eagle", "A bird of prey"}).Return(nil)
form := newCreateBirdForm()
req, err := http.NewRequest("POST", "", bytes.NewBufferString(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(createBirdHandler)
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusFound {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
mockStore.AssertExpectations(t)
}
func newCreateBirdForm() *url.Values {
form := url.Values{}
form.Set("species", "eagle")
form.Set("description", "A bird of prey")
return &form
}