Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created November 11, 2019 08:13
Show Gist options
  • Save joeke80215/169581dc44835f61defae0925c79d8a6 to your computer and use it in GitHub Desktop.
Save joeke80215/169581dc44835f61defae0925c79d8a6 to your computer and use it in GitHub Desktop.
golang gin httptest example
package service
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
type userINfo struct {
ID uint64 `json:"id"`
Name string `json:"name"`
}
func handler(c *gin.Context) {
var info userINfo
if err := c.ShouldBindJSON(&info); err != nil {
log.Panic(err)
}
fmt.Println(info)
c.Writer.Write([]byte(`{"status": 200}`))
}
func TestHandler(t *testing.T) {
rPath := "/user"
router := gin.Default()
router.GET(rPath, handler)
req, _ := http.NewRequest("GET", rPath, strings.NewReader(`{"id": "1","name": "joe"}`))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
t.Logf("status: %d", w.Code)
t.Logf("response: %s", w.Body.String())
}
@dibrinsofor
Copy link

can this be updated to assert returned values are as expected. say, using github.com/stretchr/testify/assert. (not self promo, i'm not affiliated) but i like your approach

@1cergey
Copy link

1cergey commented Nov 21, 2023

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment