feat 单元测试
This commit is contained in:
34
utils/test.go
Normal file
34
utils/test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"common/net/http/http_resp"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"net/http/httptest"
|
||||
)
|
||||
|
||||
// 给测试用例提供一些通用函数
|
||||
|
||||
// CreateTestContext 创建测试用例的上下文
|
||||
func CreateTestContext(method, path string, body interface{}) (*httptest.ResponseRecorder, *gin.Context) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
var buf bytes.Buffer
|
||||
if body != nil {
|
||||
_ = json.NewEncoder(&buf).Encode(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, &buf)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
return w, c
|
||||
}
|
||||
|
||||
// AssertResponse 断言返回值
|
||||
func AssertResponse(ts *suite.Suite, w *httptest.ResponseRecorder, httpCode int, code *http_resp.Code) {
|
||||
ts.Assert().Equal(httpCode, w.Code)
|
||||
var response map[string]interface{}
|
||||
ts.Assert().NoError(json.Unmarshal(w.Body.Bytes(), &response))
|
||||
ts.Assert().Equal(float64(code.Code()), response["code"])
|
||||
}
|
||||
Reference in New Issue
Block a user