go httpmock使用

介绍

httpmock是一款用来模拟http接口请求的工具。

在日常开发中当我们编写单元测试时,难免会遇到一些逻辑是需要请求别人的http接口,而我们无法完美模拟这些接口所需要的参数。这个时候就需要一个工具,当我们请求一些外部接口的时候拦截这些请求,并将它的返回值设置为我们预设好的结果。

安装

go get github.com/jarcoal/httpmock

使用

简单使用

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使用会有一些变化

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值