为 Gin 框架编写测试用例


基于 net/http/httptest 编写 HTTP 测试用例。

示例代码(src/gin-demo/test/router.go):

package main
    
import "github.com/gin-gonic/gin"
    
func setupRouter() *gin.Engine {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.String(200, "pong")
    })
    return r
}
    
func main() {
    r := setupRouter()
    r.Run(":8088")
}

对应的测试代码(需要和待测试代码位于同一目录下,src/gin-demo/test/router_test.go):

package main
    
import (
    "net/http"
    "net/http/httptest"
    "testing"
    
    "github.com/stretchr/testify/assert"
)
    
func TestPingRoute(t *testing.T) {
    router := setupRouter()
    
    w := httptest.NewRecorder()
    req, _ := http.NewRequest("GET", "/ping", nil)
    router.ServeHTTP(w, req)
    
    assert.Equal(t, 200, w.Code)
    assert.Equal(t, "pong", w.Body.String())
}

test 目录下运行如下测试命令进行测试:

-w449


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Gin 使用示例(四十二):XML/JSON/YAML/ProtoBuf 渲染

>> 下一篇: 没有下一篇了