go-resty / resty

Simple HTTP and REST client library for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to test Body() due to unexported variable body

BrunoKrugel opened this issue · comments

In our tests, we use mockery, so we can mock the return value of our methods.

If I isolate my HTTP request in a method and return the resty.Response struct, I cannot mock the body value.

In the following example, my GetData() method will call the SendPostRequest() method that is mocked, with mockery I will set the value return from the SendPostRequest(), that will be used afterwards in GetData().

response := resty.Response{
	RawResponse: &http.Response{
		StatusCode: 200,
		Body:          myBodyValue,
	},
}

mockery.EXPECT().SendPostRequest(mock.Anything).Return(&httpResponseMock)

responseValue := instance.GetData()

If I try to access the Body value from the response.Body() it will return nill, bacause the method returns the value from the Response struct, which is private.

type Response struct {
	Request     *Request
	RawResponse *http.Response

	body       []byte
	size       int64
	receivedAt time.Time
}

func (r *Response) Body() []byte {
	if r.RawResponse == nil {
		return []byte{}
	}
	return r.body
}

All the other methods/values available in the Response struct, return the value from the RawResponse (for example the StatusCode or Status), only the value of body comes from a different source.

Why the Body method check for RawResponse value if it will return the value of body instead of Response.Body?

How can I set a custom body value directly in the Response structure instead of the RawResponse? So I can get the value with Body().

I also found these two related issues:

#245 - The last reply from @Kolyunya its the same scenario, but in his scenario he is trying to access .String() instead of .Body()

#600 - The OP also is questioning the comparisson between RawResponse and the body.

@BrunoKrugel Thanks for reaching out. I will add Response.SetBody(b []byte) method.

@BrunoKrugel Currently, it's available in v2.10.0-rc.2. Can you please try it out?