【问题标题】:HttpMock is not intercepting Resty callHttpMock 没有拦截 Resty 调用
【发布时间】:2020-10-07 15:01:43
【问题描述】:

我有一个函数调用我想在测试中模拟出来的外部 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)

【问题讨论】:

    标签: go go-testing http-mock resty


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多