[英]HttpMock is not intercepting Resty call
我有一个 function 调用外部 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)
在 function 中,客户端具有:
httpClient: *net/http.Client {
Transport: net/http.RoundTripper(*net/http.Transport)
通过使用 function 注入 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.