0

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
  • Why not use http.Transport{} ? Commented Aug 24, 2016 at 13:09

1 Answer 1

4

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)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The errors are a separate question. You ought to accept this answer and ask a new one.
@PassionateDeveloper The test runs and fails as indicated by the first couple of lines of output. There's insufficient information to diagnose why the test fails. Perhaps ask a new question as suggested by Christopher?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.