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

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

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时,测试从来没有运行过。我理解这是因为我为这个函数定义了接收器。

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

英文:

I have a below test:

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

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

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

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

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

func TestAuthenticate(t *testing.T) {
    api := &ApiResource{} // <-- 根据需要初始化 api。
    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("缺少或错误的状态码:%d", recorder.Code)
    }
}
英文:

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

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

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

func TestAuthenticate(t *testing.T) {
    api := &amp;ApiResource{} // &lt;-- initialize api as appropriate.
	httpReq, _ := http.NewRequest(&quot;POST&quot;, &quot;/login&quot;, nil)
	req := restful.NewRequest(httpReq)

	recorder := new(httptest.ResponseRecorder)
	resp := restful.NewResponse(recorder)

	api.Authenticate(req, resp)
	if recorder.Code!= 404 {
		t.Logf(&quot;Missing or wrong status code:%d&quot;, recorder.Code)
	}
}

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:

确定