编写使用testify的Gin API的测试导致返回404 HTTP响应代码。

huangapple go评论69阅读模式
英文:

Writing test for a Gin API using testify results in a 404 HTTP response code

问题

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

I have attempted to write a test for my Gin API using testify.

Unfortunately, it responds with an unexpected HTTP 404 response code within the test.

When I execute the program I can reach the corresponding interface via curl and browser.

Why are my tests failing ?

Test code:

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

答案1

得分: 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)
}
英文:

You create a router without any handle. Add router.GET("/api/v1/statistics/projects", your handleFunc)

or

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

    yourHandleFunc(c)

    fmt.Println(recorder.Code)

}

huangapple
  • 本文由 发表于 2021年9月2日 03:53:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/69019858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定