'Testing gin based REST API not getting params while using net/http/httptest

I am developing a REST API based on Gin Go, the endpoint looks 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?



Solution 1:[1]

router.GET("/cars/1", handler) should be router.GET("/cars/:type", handler) in your test.

Note that a better (more testable; less duplication of routes) would be to create a SetupRouter() *gin.Engine function that returns all of your routes. e.g.

// package main

// server.go
// This is where you create a gin.Default() and add routes to it
func SetupRouter() *gin.Engine {
    router := gin.Default()
    router.GET("/cars/:type", carsByType)

    return router
}

func main() {
    router := SetupRouter() 
    router.Run()
}

// router_test.go
testRouter := SetupRouter()

req, err := http.NewRequest("GET", "/cars/1", nil)
if err != nil {
    fmt.Println(err)
}

resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
assert.Equal(t, resp.Code, 200)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1