package httpx import ( "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestResponseHelpers(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New() r.GET("/ok", OK) r.GET("/fail", func(c *gin.Context) { Fail(c, "bad") }) r.GET("/auth", func(c *gin.Context) { NoAuth(c, "login") }) for _, tc := range []struct { path string statusCode int body string }{ {"/ok", 200, `{"code":0,"data":{},"msg":"操作成功"}`}, {"/fail", 200, `{"code":7,"data":{},"msg":"bad"}`}, {"/auth", 401, `{"code":7,"data":null,"msg":"login"}`}, } { req := httptest.NewRequest("GET", tc.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) if w.Code != tc.statusCode || w.Body.String() != tc.body { t.Fatalf("%s: status=%d body=%q", tc.path, w.Code, w.Body.String()) } } }