go单元测试模块化(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 mocks
34     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 }

猜你喜欢

转载自www.cnblogs.com/jiayoupaofu/p/9583019.html