分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

go单元测试模块化(http请求)

发布时间:2023-09-06 02:13责任编辑:白小东关键词:http

http协议的mock可以使用 https://github.com/h2non/gock包

示例:

 1 package hellogock 2 ?3 import ( 4 ????"bytes" 5 ????"io/ioutil" 6 ????"net/http" 7 ????"testing" 8 ?9 ????"github.com/nbio/st"10 ????"gopkg.in/h2non/gock.v1"11 )12 13 func TestMockCheckpwdstrength(t *testing.T) {14 15 ????defer gock.Off()16 17 ????// mock请求的地址18 ????gock.New("https://zhuce.test.com").19 ????????Post("/regapi"). ??????????????????????????????????????????????//对应是post还是get方法20 ????????MatchType("json"). ????????????????????????????????????????????//对应的类型21 ????????JSON(map[string]string{"op": "pwdStrength", "pwd": "dddddd"}). //这里是请求时json里面所带的参数22 ????????Reply(201). ???????????????????????????????????????????????????//这里是mock出来的http返回值23 ????????JSON(map[string]string{"bar": "foo"}) ?????????????????????????//mock请求后所想要的返回值24 25 ????body := bytes.NewBuffer([]byte(`{"op": "pwdStrength", "pwd": "dddddd"}`))26 ????res, err := http.Post("https://zhuce.test.com/regapi", "application/json", body)27 ????st.Expect(t, err, nil)28 ????st.Expect(t, res.StatusCode, 201)29 30 ????resBody, _ := ioutil.ReadAll(res.Body)31 ????st.Expect(t, string(resBody)[:13], `{"bar":"foo"}`)32 33 ????// Verify that we don‘t have pending mocks34 ????st.Expect(t, gock.IsDone(), true)35 }

 一个get请求的例子

 1 func TestMockGet(t *testing.T) { 2 ????//http://10.10.98.6:6395/ip-api/v1.0/getIPInfo 3 ????//{"result":0,"error":"ip is required"} 4 ????gock.New("http://10.10.98.6:6395"). 5 ????????Get("/ip-api/v1.0/getIPInfo"). 6 ????????Reply(200). 7 ????????JSON(map[string]interface{}{ 8 ????????????"result": 1, 9 ????????????"error": ?"not found"})10 11 ????res, err := http.Get("http://10.10.98.6:6395/ip-api/v1.0/getIPInfo") //发送请求12 ????st.Expect(t, err, nil)13 ????st.Expect(t, res.StatusCode, 200) //校验结果14 15 ????resBody, _ := ioutil.ReadAll(res.Body)16 ????st.Expect(t, string(resBody)[:32], `{"error":"not found","result":1}`) //校验结果17 }

go单元测试模块化(http请求)

原文地址:https://www.cnblogs.com/jiayoupaofu/p/9583019.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved