標籤: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請求)