测试

怎样编写 Gin 的测试用例

HTTP 测试首选 net/http/httptest 包。

  1. package main
  2. func setupRouter() *gin.Engine {
  3. r := gin.Default()
  4. r.GET("/ping", func(c *gin.Context) {
  5. c.String(200, "pong")
  6. })
  7. return r
  8. }
  9. func main() {
  10. r := setupRouter()
  11. r.Run(":8080")
  12. }

上面这段代码的测试用例:

  1. package main
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestPingRoute(t *testing.T) {
  9. router := setupRouter()
  10. w := httptest.NewRecorder()
  11. req, _ := http.NewRequest("GET", "/ping", nil)
  12. router.ServeHTTP(w, req)
  13. assert.Equal(t, 200, w.Code)
  14. assert.Equal(t, "pong", w.Body.String())
  15. }

Last modified 07.03.2020 : add blog dir (#115) (f46734b)