3

I am trying to use Mockery to mock a Http client, but when I try to pass in the return value I get an error saying type http.Response is not an expression

Below is my interface and handler

type HTTPClient interface { Get(url string) (resp *http.Response, err error) } type Handler struct { httpClient HTTPClient } 

Mockery generated a mock class which looks like the below

type HTTPClient struct { mock.Mock } // Get provides a mock function with given fields: url func (_m *HTTPClient) Get(url string) (*http.Response, error) { ret := _m.Called(url) var r0 *http.Response if rf, ok := ret.Get(0).(func(string) *http.Response); ok { r0 = rf(url) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*http.Response) } } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(url) } else { r1 = ret.Error(1) } return r0, r1 } 

In my test, I am trying to mock the httpclient like below

httpClient := &mocks.HTTPClient{} httpClient.On("Get", request.SubscribeURL).Return(resp*http.Response, nil) 

I am not sure what parameters I am supposed to in Return. What should I be passing?

1 Answer 1

4

The http.Response (notice it is without square brackets, it denotes a type mostly) is an expression, while you should return actual response (a return value of the function), since a function returns two values *http.Response a pointer to http response struct and an error or nil.

body := ioutil.NopCloser(strings.NewReader("hello world")) httpRespose := &http.Response{Body: body, Status: "200 OK", StatusCode: 200} httpClient.On("Get", request.SubscribeURL) .Return( httpRespose, // http response with string in the body and the code 200 nil, // no error occured while response processed ) 
Sign up to request clarification or add additional context in comments.

1 Comment

ioutil.NopCloser is Deprecated as of Go 1.16, this function simply calls io.NopCloser.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.