登录
首页 >  Golang >  Go问答

编写测试 Gin API 会导致返回 404 HTTP 状态码

来源:stackoverflow

时间:2024-02-20 17:09:24 391浏览 收藏

大家好,我们又见面了啊~本文《编写测试 Gin API 会导致返回 404 HTTP 状态码》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我尝试使用 testify 为我的 gin api 编写测试。

不幸的是,它在测试中响应了意外的 http 404 响应代码。

当我执行程序时,可以通过curl和浏览器到达相应的界面。

为什么我的测试失败?

测试代码:

func (suite *statisticTestSuite) TestGetProjects() {
    suite.T().Log("TestGetAllProjects")

    recorder := httptest.NewRecorder()

    router := gin.Default()

    request, err := http.NewRequest(http.MethodGet, "/api/v1/statistics/projects", nil)
    request.Header = http.Header{"Content-Type": []string{"application/json"}}

    assert.NoError(suite.T(), err)

    router.ServeHTTP(recorder, request)

    data := make(map[string]interface{})
    data["projects"] = 3

    respBody, err := json.Marshal(gin.H{
        "code": 200,
        "msg":  "ok",
        "data": data,
    })

    fmt.Println(recorder.Code)
    fmt.Println(respBody)
}

正确答案


您创建了一个没有任何句柄的路由器。添加 router.get("/api/v1/statistics/projects", 你的handlefunc)

func TestHandle(t *testing.T) {
    recorder := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(recorder)

    yourHandleFunc(c)

    fmt.Println(recorder.Code)

}

好了,本文到此结束,带大家了解了《编写测试 Gin API 会导致返回 404 HTTP 状态码》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>