在项目目录下新建test 文件夹,然后在该文件下新建test.go 文件来封装一些 请求方法代码如下
type TestCase struct { Method string //请求类型 Url string //链接 ContentType string // Param string //参数 Code int //状态码 Desc string //描述 ShowBody bool //是否展示返回 ErrMsg string //错误信息 Ext1 interface{} //自定义1 Ext2 interface{} //自定义2 } func init() { //跟main.go 保持一致,用到什么就初始化什么 //初始日志 common.InitLogger() } func NewBufferString(body string) io.Reader { return bytes.NewBufferString(body) } //具体的每一个请求 func DoRequest(method, url, contentType string, body string) (c *gin.Context, r *http.Request, w *httptest.ResponseRecorder) { route := gin.New() route.Use(middleware.GinLogger(),middleware.GinRecovery(false)) route.Use(middleware.Cors()) router.InitRouter(route) if method =="" { method = "POST" //因为我的请求大部分都是post 这个为了偷懒 } w = httptest.NewRecorder() c, _ = gin.CreateTestContext(w) r = httptest.NewRequest(method, url, NewBufferString(body)) c.Request = r c.Request.Header.Set("Content-Type", contentType) c.Request.Header.Set("GINAPPKEY","100000") //按照自己需求设置自己的 header //... route.ServeHTTP(w, r) return } //执行 测试 func Exec (t *testing.T,caseList []TestCase) { for k, v := range caseList { _, _, w := DoRequest(v.Method, v.Url, v.ContentType, v.Param) fmt.Println() fmt.Printf("第%d个测试用例:%s;", k+1, v.Desc) if v.ShowBody { fmt.Printf("接口返回%s", w.Body.String()) fmt.Println() } assert.Equal(t, 200, w.Code) //result := Result(w.Body.String()) //fmt.Println("接口返回:", w.Body.String()) //assert.Equal(t, "success", result["msg"]) } }
然后载对应模块新建 _test.go 来进行测试 ,比如 我对index / product.go 测试
载test/index/ 新建product_test.go
func TestProduct(t *testing.T) { var caseList = []test.TestCase{ { Method: "POST", Url: "/api/index/product/getItems", ContentType: "application/json", Param: "", Code: 200, Desc: "商品列表接口测试", ShowBody: true, ErrMsg: "", Ext1: nil, Ext2: nil, }, { Method: "POST", Url: "/api/index/product/getItem", ContentType: "application/json", Param: `{"id":1}`, Code: 200, Desc: "商品详情接口测试", ShowBody: true, ErrMsg: "", Ext1: nil, Ext2: nil, }, } test.Exec(t,caseList) }
然后执行
go test -v ./test/index/product_test.go 可以看到以下信息
具体代码 git 地址