简体   繁体   中英

HttpMock is not intercepting Resty call

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)

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM