如何在 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


测试从来没有这样。我明白那是因为我有这个功能的接收器。


有什么方法可以测试这个东西吗?


神不在的星期二
浏览 163回答 1
1回答

慕姐8265434

该测试包可与功能,而不是方法。编写一个函数包装器来测试该方法:func TestAuthenticate(t *testing.T) {&nbsp; &nbsp;api := &ApiResource{} // <-- initialize api as appropriate.&nbsp; &nbsp;api.TestAuthenticate(t)}您可以将所有代码移动到测试函数并消除该方法:func TestAuthenticate(t *testing.T) {&nbsp; &nbsp; api := &ApiResource{} // <-- initialize api as appropriate.&nbsp; &nbsp; httpReq, _ := http.NewRequest("POST", "/login", nil)&nbsp; &nbsp; req := restful.NewRequest(httpReq)&nbsp; &nbsp; recorder := new(httptest.ResponseRecorder)&nbsp; &nbsp; resp := restful.NewResponse(recorder)&nbsp; &nbsp; api.Authenticate(req, resp)&nbsp; &nbsp; if recorder.Code!= 404 {&nbsp; &nbsp; &nbsp; &nbsp; t.Logf("Missing or wrong status code:%d", recorder.Code)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go