funcTestFetchArticles(t*testing.T) {
httpmock.Activate()
deferhttpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))
// do stuff that makes a request to articles.json
}
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.json",
func(req*http.Request) (*http.Response, error) {
resp, err:=httpmock.NewJsonResponse(200, articles)
iferr!=nil {
returnhttpmock.NewStringResponse(500, ""), nil
}
returnresp, nil
},
)
// mock to add a new articlehttpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json",
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
}