Hey so I have seen and used this post to help mock my http.Client but when I try to pass the mock request I get the following error: cannot use mockClient (variable of type *MockClient) as *"net/http".Client value in argument to api.callAPI.
In one file I have my actual code:
I created the HTTPClient:
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
I have the function that passes the HTTPClient as an interface (I can't show all of it because it is for work but here's the important pieces):
func (api *API) callAPI(req *http.Request, client HTTPClient) (utils.ErrorWrapper, bool) {
response, err := client.Do(req)
}
I also have another function that calls the callAPI method. In that function I create client variable right before I call the callAPI function
var Client HTTPClient = &http.Client{}
response, isRetry := api.callAPI(req, Client)
This all works fine. However, in my testing file I get the error as mentioned above. I am using testify for my mocking framework. Here is what I have in my testing file (both the testing file and the actual code are apart of the same package):
set up my mock client and the Do function using testify
type MockClient struct {
mock.Mock
}
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
args := m.Called()
resp := args.Get(0)
return resp.(*http.Response), args.Error(1)
}
Then create my test:
func TestCallAPI(t *testing.T) {
mockClient := &MockClient{}
recorder := httptest.NewRecorder()
responseCh := make(chan utils.ErrorWrapper)
c, _ := gin.CreateTestContext(recorder)
id:= "unitTest123"
api := NewAPICaller(responseCh, id, c)
var response = Response{
StatusCode: 200,
}
//setup expectations
mockClient.On("Do").Return(response, nil)
req, _ := http.NewRequest("GET", "URL I Can't Show", nil)
wrapper, isRetry := api.callAPI(req, mockClient)
mockClient.AssertExpectations(t)
assert.Equal(t, "placeholder", wrapper)
assert.Equal(t, false, isRetry)
}
I tried to do a similar thing with the mockclient variable the way I did with the Client variable:
var mockclient HTTPClient = &MockClient{}
but I get this error on the HTTPClient: undeclared name: HTTPClient. Unsure why this is happening because they are a part of the same package so I thought it could be exported easily?