1/* 2Package httpmock provides tools for mocking HTTP responses. 3 4Simple Example: 5 func TestFetchArticles(t *testing.T) { 6 httpmock.Activate() 7 defer httpmock.DeactivateAndReset() 8 9 // Exact URL match 10 httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles", 11 httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) 12 13 // Regexp match (could use httpmock.RegisterRegexpResponder instead) 14 httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/\d+\z`, 15 httpmock.NewStringResponder(200, `{"id": 1, "name": "My Great Article"}`)) 16 17 // do stuff that makes a request to articles 18 19 // get count info 20 httpmock.GetTotalCallCount() 21 22 // get the amount of calls for the registered responder 23 info := httpmock.GetCallCountInfo() 24 info["GET https://api.mybiz.com/articles"] // number of GET calls made to https://api.mybiz.com/articles 25 info["GET https://api.mybiz.com/articles/id/12"] // number of GET calls made to https://api.mybiz.com/articles/id/12 26 info[`GET =~^https://api\.mybiz\.com/articles/id/\d+\z`] // number of GET calls made to https://api.mybiz.com/articles/id/<any-number> 27 } 28 29Advanced Example: 30 func TestFetchArticles(t *testing.T) { 31 httpmock.Activate() 32 defer httpmock.DeactivateAndReset() 33 34 // our database of articles 35 articles := make([]map[string]interface{}, 0) 36 37 // mock to list out the articles 38 httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles", 39 func(req *http.Request) (*http.Response, error) { 40 resp, err := httpmock.NewJsonResponse(200, articles) 41 if err != nil { 42 return httpmock.NewStringResponse(500, ""), nil 43 } 44 return resp, nil 45 }, 46 ) 47 48 // return an article related to the request with the help of regexp submatch (\d+) 49 httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/(\d+)\z`, 50 func(req *http.Request) (*http.Response, error) { 51 // Get ID from request 52 id := httpmock.MustGetSubmatchAsUint(req, 1) // 1=first regexp submatch 53 return httpmock.NewJsonResponse(200, map[string]interface{}{ 54 "id": id, 55 "name": "My Great Article", 56 }) 57 }, 58 ) 59 60 // mock to add a new article 61 httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles", 62 func(req *http.Request) (*http.Response, error) { 63 article := make(map[string]interface{}) 64 if err := json.NewDecoder(req.Body).Decode(&article); err != nil { 65 return httpmock.NewStringResponse(400, ""), nil 66 } 67 68 articles = append(articles, article) 69 70 resp, err := httpmock.NewJsonResponse(200, article) 71 if err != nil { 72 return httpmock.NewStringResponse(500, ""), nil 73 } 74 return resp, nil 75 }, 76 ) 77 78 // do stuff that adds and checks articles 79 } 80*/ 81package httpmock 82