Go Unit Test modularity (HTTP request)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.