【发布时间】:2018-03-14 03:07:15
【问题描述】:
我编写了一个客户端,它通过 REST 端点连接到服务器。客户端需要发出一连串 11 个不同的请求来完成一个动作(这是一个rococo 备份系统)。
我正在用 Go 编写我的客户端,我也想用 Go 编写我的模拟/测试。我不清楚的是名为func TestMain 的测试如何调用客户端的func main(),以测试11 个请求链的完成情况。
我的客户端的二进制文件将通过以下方式从 shell 运行:
$ client_id=12345 region=apac3 backup
如何从测试中调用func main(),并设置环境变量?还是有其他方法? (我是comfortable writing tests,所以这不是问题)
我正在查看jarcoal/httpmock 中的高级示例(但我可以使用另一个库)。例子最后说// do stuff that adds and checks articles,那是我要打电话给main()的地方吗?
我已经粘贴了下面的高级示例,以供将来参考。
func TestFetchArticles(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
// our database of articles
articles := make([]map[string]interface{}, 0)
// mock to list out the articles
httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
func(req *http.Request) (*http.Response, error) {
resp, err := httpmock.NewJsonResponse(200, articles)
if err != nil {
return httpmock.NewStringResponse(500, ""), nil
}
return resp, nil
},
)
// mock to add a new article
httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json",
func(req *http.Request) (*http.Response, error) {
article := make(map[string]interface{})
if err := json.NewDecoder(req.Body).Decode(&article); err != nil {
return httpmock.NewStringResponse(400, ""), nil
}
articles = append(articles, article)
resp, err := httpmock.NewJsonResponse(200, article)
if err != nil {
return httpmock.NewStringResponse(500, ""), nil
}
return resp, nil
},
)
// do stuff that adds and checks articles
}
【问题讨论】:
标签: rest testing go mocking integration-testing