亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中將測試編寫為方法?

如何在 Go 中將測試編寫為方法?

Go
神不在的星期二 2021-08-23 15:36:36
我有以下測試:package api_appfunc (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測試從來沒有這樣。我明白那是因為我有這個功能的接收器。有什么方法可以測試這個東西嗎?
查看完整描述

1 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

該測試包可與功能,而不是方法。編寫一個函數包裝器來測試該方法:


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)

    }

}


查看完整回答
反對 回復 2021-08-23
  • 1 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號