繁体   English   中英

如何在Go中将测试作为方法编写?

[英]How to write a test as a method in 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

测试永远不会失败。 我知道那是因为我有该功能的接收器。

有办法测试一下吗?

测试包使用功能而不是方法。 编写函数包装器以测试方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM