Passionate Engineer
Passionate Engineer

Reputation: 10412

How to write a test as a method in Go?

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?

Upvotes: 0

Views: 142

Answers (1)

user4122236
user4122236

Reputation:

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

func TestAuthenticate(t *testing.T) {
   api := &ApiResource{} // <-- 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 := &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)
    }
}

Upvotes: 4

Related Questions