Testing

How to write test case for Gin?

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

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

Test for code example above:

  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 January 12, 2021 : Adjust testing index (#158) (e178d63)