go單元測試模組化(http請求)

來源:互聯網
上載者:User

標籤:dal   check   expect   import   gap   not   port   line   test   

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請求)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.