英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论