这个好像没什么好讲,主要是gin框架下,httptest包要怎么写,这个是重点。直接上代码吧。

main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
"net/http"
"github.com/gin-gonic/gin"
)

func main() {
router := SetupRouter()
router.Run()
}

func SetupRouter() *gin.Engine {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hello": "world",
})
})

return router
}

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
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(method, path, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}

func TestHelloWorld(t *testing.T) {
// Build our expected body
body := gin.H{
"hello": "world",
}
// Grab our router
router := SetupRouter()
// Perform a GET request with that handler.
w := performRequest(router, "GET", "/")
// Assert we encoded correctly,
// the request gives a 200
assert.Equal(t, http.StatusOK, w.Code)
// Convert the JSON response to a map
var response map[string]string
err := json.Unmarshal([]byte(w.Body.String()), &response)
// Grab the value & whether or not it exists
value, exists := response["hello"]
// Make some assertions on the correctness of the response.
assert.Nil(t, err)
assert.True(t, exists)
assert.Equal(t, body["hello"], value)
}

代码:Testing Gin — JSON Responses