[英]How to write a test as a method in Go?
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? 有办法测试一下吗?
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.