I am developing a REST API based on Gin golang, the endpoint look something like below:
func carsByType(c *gin.Context) {
fmt.Println("Go Request in Handler...")
carType := c.Params.ByName("type")
fmt.Println(carType)
if carType != "" {
}
c.JSON(http.StatusBadRequest, gin.H{"result": "Bad request"})
return
}
func main() {
router := gin.Default()
router.GET("/cars/:type", carsByType)
router.Run(":80")
}
When I am making request to the endpoint via browser and cURL its just working fine, getting the carType value but when I am running the tests its returning bad request and getting carType is "".
For testing the endpoint my test code looks like this:
func TestGetcarsByType(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := carsByType
router := gin.Default()
router.GET("/cars/1", handler)
req, err := http.NewRequest("GET", "/cars/1", nil)
if err != nil {
fmt.Println(err)
}
resp := httptest.NewRecorder()
router.ServeHTTP(resp, req)
assert.Equal(t, resp.Code, 200)
}
What am I doing wrong?
router.GET("/cars/1", handler)
should berouter.GET("/cars/:type", handler)
in your test. – elithrar