英文:
How to write a test as a method in Go?
问题
我有一个以下的测试:
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
时,测试从来没有运行过。我理解这是因为我为这个函数定义了接收器。
有没有办法我们可以测试这个东西?
英文:
I have a below test:
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)
}
}
I want to test this function but when I do
go test api_app -v
The test never rungs this. I understand that's because I have receiver for the function.
Is there a way we can test this thing?
答案1
得分: 4
测试包 适用于函数,而不是方法。编写一个函数包装器来测试该方法:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{} // <-- 根据需要初始化 api。
api.TestAuthenticate(t)
}
你可以将所有代码移到测试函数中并消除该方法:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{} // <-- 根据需要初始化 api。
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("缺少或错误的状态码:%d", recorder.Code)
}
}
英文:
The testing package works with functions, not methods. Write a function wrapper to test the method:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{} // <-- initialize api as appropriate.
api.TestAuthenticate(t)
}
You can move all of the code to the test function and eliminate the method:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论