【问题标题】:Writing test for a Gin API using testify results in a 404 HTTP response code使用 testify 为 Gin API 编写测试会导致 404 HTTP 响应代码
【发布时间】:2021-09-01 19:53:24
【问题描述】:

我尝试使用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)
}

【问题讨论】:

    标签: go go-gin testify


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 2021-09-11
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      相关资源
      最近更新 更多