Reputation: 1884
I have a function that calls an external api that I want to mock out in the test.
func ApiWrapper(...) (...) {
client := resty.New()
var r apiResponse
apiPath := "..." // In the test will be http://localhost:{PORT}/path/to/endpoint
_, e := client.R().SetResult(&r).Get(apiPath)
...
return ...
}
The test looks like this:
func TestApiWrapper(t *testing.T) {
client := resty.New()
httpmock.ActivateNonDefault(client.GetClient())
defer httpmock.DeactivateAndReset()
mock_resp = `...`
responder := httpmock.NewStringResponder(200, mock_resp)
api_url := "same string used in the function"
httpmock.RegisterResponder("GET", api_url, responder)
res, e := ApiWrapper(...)
...
}
The issue I'm having is that the mock is not being used also the external api will not be available in our CI.
In the test the client has:
httpClient: *net/http.Client {
Transport: net/http.RoundTripper(*github.com/jarcoal/httpmock.MockTransport)
In the function the client has:
httpClient: *net/http.Client {
Transport: net/http.RoundTripper(*net/http.Transport)
Upvotes: 0
Views: 2177
Reputation: 1884
I was able to get around the problem by using a function to inject the resty Client. Don't really like this approach as it leaves a couple of lines of code that are not executed during my test.
func ApiWrapper(...) {
client := resty.New()
resp, err := ApiWrapperWrapper(client)
return resp, err
}
func ApiWrapperWrapper(client *resty.Client) (...) {
copy all the code into here
}
Then in my test I just call ApiWrapperWrapper and pass in the mocked client.
func TestApiWrapper(...) {
...
// change last line in example to this
res, e := ApiWrapperWrapper(client)
}
Upvotes: 1