如何在Go中编写一个作为方法的测试?

huangapple go评论110阅读模式
英文:

How to write a test as a method in Go?

问题

我有一个以下的测试:

  1. package api_app
  2. func (api *ApiResource) TestAuthenticate(t *testing.T) {
  3. httpReq, _ := http.NewRequest("POST", "/login", nil)
  4. req := restful.NewRequest(httpReq)
  5. recorder := new(httptest.ResponseRecorder)
  6. resp := restful.NewResponse(recorder)
  7. api.Authenticate(req, resp)
  8. if recorder.Code != 404 {
  9. t.Logf("Missing or wrong status code:%d", recorder.Code)
  10. }
  11. }

我想测试这个函数,但是当我运行go test api_app -v时,测试从来没有运行过。我理解这是因为我为这个函数定义了接收器。

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

英文:

I have a below test:

  1. package api_app
  2. func (api *ApiResource) TestAuthenticate(t *testing.T) {
  3. httpReq, _ := http.NewRequest("POST", "/login", nil)
  4. req := restful.NewRequest(httpReq)
  5. recorder := new(httptest.ResponseRecorder)
  6. resp := restful.NewResponse(recorder)
  7. api.Authenticate(req, resp)
  8. if recorder.Code!= 404 {
  9. t.Logf("Missing or wrong status code:%d", recorder.Code)
  10. }
  11. }

I want to test this function but when I do

go test api_app -v

The test never rungs this. I understand that's because I have receiver for the function.

Is there a way we can test this thing?

答案1

得分: 4

测试包 适用于函数,而不是方法。编写一个函数包装器来测试该方法:

  1. func TestAuthenticate(t *testing.T) {
  2. api := &ApiResource{} // <-- 根据需要初始化 api。
  3. api.TestAuthenticate(t)
  4. }

你可以将所有代码移到测试函数中并消除该方法:

  1. func TestAuthenticate(t *testing.T) {
  2. api := &ApiResource{} // <-- 根据需要初始化 api。
  3. httpReq, _ := http.NewRequest("POST", "/login", nil)
  4. req := restful.NewRequest(httpReq)
  5. recorder := new(httptest.ResponseRecorder)
  6. resp := restful.NewResponse(recorder)
  7. api.Authenticate(req, resp)
  8. if recorder.Code != 404 {
  9. t.Logf("缺少或错误的状态码:%d", recorder.Code)
  10. }
  11. }
英文:

The testing package works with functions, not methods. Write a function wrapper to test the method:

  1. func TestAuthenticate(t *testing.T) {
  2. api := &amp;ApiResource{} // &lt;-- initialize api as appropriate.
  3. api.TestAuthenticate(t)
  4. }

You can move all of the code to the test function and eliminate the method:

  1. func TestAuthenticate(t *testing.T) {
  2. api := &amp;ApiResource{} // &lt;-- initialize api as appropriate.
  3. httpReq, _ := http.NewRequest(&quot;POST&quot;, &quot;/login&quot;, nil)
  4. req := restful.NewRequest(httpReq)
  5. recorder := new(httptest.ResponseRecorder)
  6. resp := restful.NewResponse(recorder)
  7. api.Authenticate(req, resp)
  8. if recorder.Code!= 404 {
  9. t.Logf(&quot;Missing or wrong status code:%d&quot;, recorder.Code)
  10. }
  11. }

huangapple
  • 本文由 发表于 2014年10月10日 00:23:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26283385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定