2014-10-09 76 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