When vendoring is used, v1 branch has to be specified. Two choices here:
preferred way:
govendor fetch github.com/jarcoal/httpmock@v1
then in go files:
import"github.com/jarcoal/httpmock"
old way (before v1 was set as default branch), use gopkg to read from
v1 branch:
govendor fetch gopkg.in/jarcoal/httpmock.v1
then in go files:
import"gopkg.in/jarcoal/httpmock.v1"
Usage
Simple Example:
funcTestFetchArticles(t*testing.T) {
httpmock.Activate()
deferhttpmock.DeactivateAndReset()
// Exact URL matchhttpmock.RegisterResponder("GET", "https://api.mybiz.com/articles",
httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))
// Regexp match (could use httpmock.RegisterRegexpResponder instead)httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/\d+\z`,
httpmock.NewStringResponder(200, `{"id": 1, "name": "My Great Article"}`))
// do stuff that makes a request to articles...// get count infohttpmock.GetTotalCallCount()
// get the amount of calls for the registered responderinfo:=httpmock.GetCallCountInfo()
info["GET https://api.mybiz.com/articles"] // number of GET calls made to https://api.mybiz.com/articlesinfo["GET https://api.mybiz.com/articles/id/12"] // number of GET calls made to https://api.mybiz.com/articles/id/12info[`GET =~^https://api\.mybiz\.com/articles/id/\d+\z`] // number of GET calls made to https://api.mybiz.com/articles/id/<any-number>
}
Advanced Example:
funcTestFetchArticles(t*testing.T) {
httpmock.Activate()
deferhttpmock.DeactivateAndReset()
// our database of articlesarticles:=make([]map[string]interface{}, 0)
// mock to list out the articleshttpmock.RegisterResponder("GET", "https://api.mybiz.com/articles",
func(req*http.Request) (*http.Response, error) {
resp, err:=httpmock.NewJsonResponse(200, articles)
iferr!=nil {
returnhttpmock.NewStringResponse(500, ""), nil
}
returnresp, nil
},
)
// return an article related to the request with the help of regexp submatch (\d+)httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/(\d+)\z`,
func(req*http.Request) (*http.Response, error) {
// Get ID from requestid:=httpmock.MustGetSubmatchAsUint(req, 1) // 1=first regexp submatchreturnhttpmock.NewJsonResponse(200, map[string]interface{}{
"id": id,
"name": "My Great Article",
})
},
)
// mock to add a new articlehttpmock.RegisterResponder("POST", "https://api.mybiz.com/articles",
func(req*http.Request) (*http.Response, error) {
article:=make(map[string]interface{})
iferr:=json.NewDecoder(req.Body).Decode(&article); err!=nil {
returnhttpmock.NewStringResponse(400, ""), nil
}
articles=append(articles, article)
resp, err:=httpmock.NewJsonResponse(200, article)
iferr!=nil {
returnhttpmock.NewStringResponse(500, ""), nil
}
returnresp, nil
},
)
// do stuff that adds and checks articles
}
Algorithm
When GET http://example.tld/some/path?b=12&a=foo&a=bar request is
caught, all standard responders are checked against the following URL
or paths, the first match stops the search:
请发表评论