The HTTP protocol mock can use the Https://github.com/h2non/gock package
Example:
1 PackageHellogock2 3 Import (4"Bytes"5"Io/ioutil"6"Net/http"7"Testing"8 9"Github.com/nbio/st"Ten"Gopkg.in/h2non/gock.v1" One ) A -Func testmockcheckpwdstrength (T *testing. T) { - the defer gock. OFF () - - //the address of the mock request -Gock. New ("https://zhuce.test.com"). +Post ("/regapi").//whether the corresponding post or get method -MatchType ("JSON").//the corresponding type +JSON (map[string]string{"op": "Pwdstrength", "pwd": "DDDDDD"}).//here is the parameter contained in the JSON when requested AReply (201).//Here's the mock HTTP return value. atJSON (map[string]string{"bar": "foo"})//The return value you want after the mock request - -Body: = bytes. Newbuffer ([]byte(' {' op ': ' Pwdstrength ', ' pwd ': ' dddddd '}`)) -Res, ERR: = http. Post ("Https://zhuce.test.com/regapi", "Application/json", body) - St. Expect (t, err, nil) -St. Expect (t, Res. StatusCode, 201) in -Resbody, _: =Ioutil. ReadAll (Res. Body) toSt. Expect (t, String (Resbody) [:], ' {' Bar ': ' foo '}`) + - //Verify that we don ' t have pending mocks theSt. Expect (t, Gock. IsDone (),true) *}
Example of a GET request
1Func Testmockget (T *testing. T) {2 //http://10.10.98.6: 6395/ip-api/v1.0/getipinfo3 //{"Result": 0, "error": "IP is required"}4Gock. New ("http://10.10.98.6:6395").5Get ("/ip-api/v1.0/getipinfo").6Reply (200).7JSON (Map[string]Interface{}{8"Result": 1,9"Error": "Not Found"})Ten OneRes, ERR: = http. Get ("Http://10.10.98.6:6395/ip-api/v1.0/getIPInfo")//Send Request A St. Expect (t, err, nil) -St. Expect (t, Res. StatusCode, 200)//Check Results - theResbody, _: =Ioutil. ReadAll (Res. Body) -St. Expect (t, String (resbody) [: +], ' {' Error ': ' Not found ', ' Result ': 1} ')//Check Results -}
Go Unit Test modularity (HTTP request)