2014-10-09 71 views
0

我有如下的测试:如何在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

测试从未梯级这一点。我明白那是因为我有这个功能的接收器。

有没有办法可以测试这个东西?

+0

为什么不使用'http.Transport {}'? – KingRider 2016-08-24 13:09:52

回答

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) 
    } 
} 
+0

我现在正在收到错误。我已更新我的问题 – 2014-10-09 17:01:46

+1

错误是一个单独的问题。你应该接受这个答案,并要求一个新的答案。 – Crisfole 2014-10-09 17:08:21

+0

@PassionateDeveloper测试运行并失败,如前几行输出所示。没有足够的信息来诊断测试失败的原因。也许问克里斯托弗建议的一个新问题? – 2014-10-09 20:46:23