forked from aeneasr/workshop-dbg
/
main_test.go
80 lines (65 loc) · 2.06 KB
/
main_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
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gorilla/mux"
"github.com/parnurzeal/gorequest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var mockedContactList = Contacts{
{
ID: "john-bravo",
Name: "John Bravo",
Department: "IT",
Company: "ACME Inc",
},
{
ID: "cathrine-mueller",
Name: "Cathrine Müller",
Department: "HR",
Company: "Grove AG",
},
}
var mockContact = Contact{
ID: "eddie-markson",
Name: "Eddie Markson",
Department: "Finance",
Company: "ACME Inc",
}
func TestListContacts(t *testing.T) {
// Initialize everything (very similar to main() function).
router := mux.NewRouter()
router.HandleFunc("/", ListContacts(&mockedContactList)).Methods("GET")
ts := httptest.NewServer(router)
// This helper function makes an http request to ListContacts and validates its output.
fetchAndTestContactList(t, ts, mockedContactList)
}
func TestAddContacts(t *testing.T) {
router := mux.NewRouter()
router.HandleFunc("/", AddContact(&mockedContactList)).Methods("POST")
router.HandleFunc("/", ListContacts(&mockedContactList)).Methods("GET")
ts := httptest.NewServer(router)
// We are expecting that our new contact is now in the list of contacts.
expectContactList := append(mockedContactList, mockContact)
_, body, errs := gorequest.New().Post(ts.URL).SendStruct(mockContact).End()
require.Len(t, errs, 0)
require.Empty(t, body)
// Like in TestListContacts, this helper function makes an http request to ListContacts and validates its output.
fetchAndTestContactList(t, ts, expectContactList)
}
func fetchAndTestContactList(t *testing.T, ts *httptest.Server, compareWith Contacts) {
// Request ListContacts
resp, err := http.Get(ts.URL)
// Verify that no errors occurred
require.Nil(t, err)
// Unmarshal the output
var result Contacts
err = json.NewDecoder(resp.Body).Decode(&result)
// Make sure that no error occurred
require.Nil(t, err)
// Compare the outputs
assert.Equal(t, compareWith, result)
}