我有一个以下测试:
package api_app
func (api *ApiResource) TestAuthenticate(t *testing.T) {
httpReq, _ := http.NewRequest("POST", "/login", nil)
req := restful.NewRequest(httpReq)
recorder := new(httptest.ResponseRecorder)
resp := restful.NewResponse(recorder)
api.Authenticate(req, resp)
if recorder.Code!= 404 {
t.Logf("Missing or wrong status code:%d", recorder.Code)
}
}
我想测试这个功能,但是当我做
时 go test api_app -v
测试从未打破过这个问题。我明白这是因为我有功能的接收器。
我们有办法测试这件事吗?
答案 0 :(得分:4)
testing package适用于函数,而不是方法。编写函数包装器来测试方法:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{} // <-- initialize api as appropriate.
api.TestAuthenticate(t)
}
您可以将所有代码移动到测试函数并删除方法:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{} // <-- initialize api as appropriate.
httpReq, _ := http.NewRequest("POST", "/login", nil)
req := restful.NewRequest(httpReq)
recorder := new(httptest.ResponseRecorder)
resp := restful.NewResponse(recorder)
api.Authenticate(req, resp)
if recorder.Code!= 404 {
t.Logf("Missing or wrong status code:%d", recorder.Code)
}
}