-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
104 lines (77 loc) · 2.28 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
98
99
100
101
102
103
104
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/buabaj/post-api/controllers"
"github.com/buabaj/post-api/initializers"
"github.com/buabaj/post-api/models"
"github.com/gin-gonic/gin"
)
func init() {
initializers.EmptyDB()
initializers.DB.AutoMigrate(&models.Post{})
}
func setUpRouter() *gin.Engine {
r := gin.Default()
return r
}
func TestRootHandler(t *testing.T) {
mockResponse := `{"message":"welcome to the post api"}`
r := setUpRouter()
r.GET("/", controllers.Root)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
r.ServeHTTP(w, req)
responseData, _ := ioutil.ReadAll(w.Body)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, mockResponse, string(responseData))
}
func TestCreatePostHandler(t *testing.T) {
r := setUpRouter()
r.POST("/posts", controllers.CreatePost)
post := models.Post{Title: "test title", Body: "test body"}
jsonData, _ := json.Marshal(post)
req, _ := http.NewRequest("POST", "/posts", bytes.NewBuffer(jsonData))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code)
}
func TestGetPostsHandler(t *testing.T) {
r := setUpRouter()
r.GET("/posts", controllers.GetPosts)
req, _ := http.NewRequest("GET", "/posts", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestGetPostHandler(t *testing.T) {
r := setUpRouter()
r.GET("/posts/:id", controllers.GetPost)
req, _ := http.NewRequest("GET", "/posts/1", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestUpdatePostHandler(t *testing.T) {
r := setUpRouter()
r.PUT("/posts/:id", controllers.UpdatePost)
post := models.Post{Title: "test title", Body: "test body"}
jsonData, _ := json.Marshal(post)
req, _ := http.NewRequest("PUT", "/posts/1", bytes.NewBuffer(jsonData))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestDeletePostHandler(t *testing.T) {
r := setUpRouter()
r.DELETE("/posts/:id", controllers.DeletePost)
req, _ := http.NewRequest("DELETE", "/posts/1", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}