-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
97 lines (81 loc) · 2.32 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
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"
"testing"
)
func TestTomHandler(t *testing.T) {
// Test GET method
t.Run("GET method", func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(TomHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Person{Id: 1, Name: "Tom", Age: 20}
var result Person
if err := json.NewDecoder(rr.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
result, expected)
}
})
// Test POST method
t.Run("POST method", func(t *testing.T) {
newPerson := Person{Name: "Jerry", Age: 25}
body, err := json.Marshal(newPerson)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, "/", bytes.NewBuffer(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(TomHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expectedResponse := "OK"
if rr.Body.String() != expectedResponse {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expectedResponse)
}
if Tom != newPerson {
t.Errorf("global Tom variable not updated: got %v want %v",
Tom, newPerson)
}
})
// Test method not allowed
t.Run("Method not allowed", func(t *testing.T) {
req, err := http.NewRequest(http.MethodPut, "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(TomHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusMethodNotAllowed {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusMethodNotAllowed)
}
expectedResponse := "Method not allowed\n"
if rr.Body.String() != expectedResponse {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expectedResponse)
}
})
}