测试基于 gin 的 REST API 在使用 net/http/httptest 时未获取参数

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

我正在开发基于 Gin Go 的 REST API,端点如下所示:

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")
}

当我通过浏览器和 cURL 向端点发出请求时,它工作正常,获取 carType 值,但是当我 运行 测试时,它返回错误请求并获取 carType 为“”。

为了测试端点,我的测试代码如下所示:

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)
}       

我做错了什么?

router.GET("/cars/1", handler) 在你的测试中应该是 router.GET("/cars/:type", handler)

请注意,更好(更可测试;路由重复更少)是创建一个 SetupRouter() *gin.Engine 函数,returns 所有路由。例如

// 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)