Reputation: 333
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)
}
Upvotes: 1
Views: 658
Reputation: 636
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)
}
Upvotes: 1