Go2 min read
go httpmock使用
介绍在 Go 单元测试中使用 httpmock 拦截外部 HTTP 请求、构造返回结果,并结合 resty 与 suite 组织更完整的接口测试。

介绍
httpmock是一款用来模拟http接口请求的工具。
在日常开发中当我们编写单元测试时,难免会遇到一些逻辑是需要请求别人的http接口,而我们无法完美模拟这些接口所需要的参数。这个时候就需要一个工具,当我们请求一些外部接口的时候拦截这些请求,并将它的返回值设置为我们预设好的结果。
安装
go get github.com/jarcoal/httpmock
使用
简单使用
[language: go]
type Response struct {
Message string 'json:"message"'
}
func TestHttpMock(t *testing.T){
httpmock.Activate()
url := "http://xxxxxx"
responder, _ := httpmock.NewJsonResponder(http.StatusOK, Response{Message: "success"})
httpmock.RegisterResponder(
// 设置拦截的http方法
"GET",
// 设置需要拦截的url
url,
// 设置需要替换成什么返回值
responder,
)
// TODO http接口请求相关代码, httpmock将会拦截该请求,并将请求结果替换为设置的结果
res, _ := http.Get(url)
defer res.Body.Close()
response := Response
body, _ := ioutil.ReadAll(res.Body)
err = json.Unmarshal(body, &response)
fmt.Println(response.Message)
}
httpmock配合resty使用会有一些变化
[language: go]
type Response struct {
Message string 'json:"message"'
}
func TestHttpMock(t *testing.T){
client := resty.New()
httpmock.DeactivateAndReset()
httpmock.ActivateNonDefault(client.GetClient())
url := "http://xxxxxx"
responder, _ := httpmock.NewJsonResponder(http.StatusOK, Response{Message: "success"})
httpmock.RegisterResponder(
// 设置拦截的http方法
"GET",
// 设置需要拦截的url
url,
// 设置需要替换成什么返回值
responder,
)
// TODO http接口请求相关代码, httpmock将会拦截该请求,并将请求结果替换为设置的结果
// 如果请求是在其它地方进行的,务必要保证client是同一个client,而不是通过resty.New重新创建的client,否则将无法拦截到对应的请求
res, _ := client.R().Get(url)
err = json.Unmarshal(res.Body(), &response)
fmt.Println(response.Message)
}
httpmock除了直接拦截http请求之外,一般和suite结合使用编写更为详细完整的接口单元测试
参考资料:httpmock github