-1

我有一个函数调用我想在测试中模拟的外部 api。

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

测试看起来像这样:

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

我遇到的问题是模拟没有被使用,外部 api 在我们的 CI 中也将不可用。

在测试中,客户有:

httpClient: *net/http.Client {
    Transport: net/http.RoundTripper(*github.com/jarcoal/httpmock.MockTransport)

在客户端具有的功能中:

httpClient: *net/http.Client {
    Transport: net/http.RoundTripper(*net/http.Transport)
4

1 回答 1

1

我能够通过使用一个函数来注入 resty Client 来解决这个问题。不太喜欢这种方法,因为它会留下几行在我的测试期间未执行的代码。

func ApiWrapper(...) {
  client := resty.New()
  resp, err := ApiWrapperWrapper(client)
  return resp, err
}

func ApiWrapperWrapper(client *resty.Client) (...) {
   copy all the code into here
}

然后在我的测试中,我只调用 ApiWrapperWrapper 并传入模拟客户端。

func TestApiWrapper(...) {
  ...
  // change last line in example to this
  res, e := ApiWrapperWrapper(client)
}
于 2020-06-17T21:19:51.790 回答