The net/http/httptest package is preferable way for HTTP testing.

    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. }