golang gin testing
package main import ( "net/http" "github.com/gin-gonic/gin" ) type LoginInput struct { Username string `json:"username"` Password string `json:"password"` } func Login(c *gin.Context) { body := LoginInput{} c.ShouldBindJSON(&body) c.Set("content-type", "application/json") c.JSON(http.StatusOK, gin.H{ "data": body, }) } func main() { router := SetupRouter() router.Run() } func SetupRouter() *gin.Engine { router := gin.Default() router.POST("/api/v1/login", Login) return router } // ================================================================== package main import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) type Response struct { Data LoginInput `json:"data"` } var router = SetupRouter() func TestLogin(t *testing.T) { t.Run("Example login", func(t *testing.T) { payload := LoginInput{} payload.Username = "restuwahyu13@gmail.com" payload.Password = "qwerty12" encoded, err := json.Marshal(payload) if err != nil { t.FailNow() } rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPost, "/api/v1/login", bytes.NewBuffer(encoded)) req.Header.Set("Content-Type", "application/json") if err != nil { t.FailNow() } router.ServeHTTP(rr, req) // not with struct // res := make(map[string]interface{}) // json.NewDecoder(rr.Body).Decode(&res) // parse := res["data"].(map[string]interface{}) // assert.Equal(t, rr.Code, 200) // assert.Equal(t, parse["username"], "restuwahyu13@gmail.com") // assert.Equal(t, parse["password"], "qwerty12") // with struct resStruct := Response{} json.NewDecoder(rr.Body).Decode(&resStruct) assert.Equal(t, rr.Code, 200) assert.Equal(t, resStruct.Data.Username, "restuwahyu13@gmail.com") assert.Equal(t, resStruct.Data.Password, "qwerty12") }) }
go gin unit test
follow this my tutorial for simple implementation, easy to undestand https://github.com/restuwahyu13/gin-unit-testing