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