戈朗HTTP REST模拟
我正在编写一个连接到具有REST端点的服务器的客户机。客户端需要发出11个不同请求的链来完成一个操作(这是一个备份系统) 我正在用Go编写我的客户机,我还想用Go编写我的模拟/测试。我不清楚的是一个名为戈朗HTTP REST模拟,rest,testing,go,mocking,integration-testing,Rest,Testing,Go,Mocking,Integration Testing,我正在编写一个连接到具有REST端点的服务器的客户机。客户端需要发出11个不同请求的链来完成一个操作(这是一个备份系统) 我正在用Go编写我的客户机,我还想用Go编写我的模拟/测试。我不清楚的是一个名为func TestMain的测试如何调用客户端的func main(),以测试11个请求链的完成情况 我的客户端二进制文件将通过以下方式从shell运行: $client\u id=12345 region=apac3备份 设置了环境变量后,如何从测试中调用func main()?还是有其他办法?
func TestMain
的测试如何调用客户端的func main()
,以测试11个请求链的完成情况
我的客户端二进制文件将通过以下方式从shell运行:
$client\u id=12345 region=apac3备份
设置了环境变量后,如何从测试中调用func main()
?还是有其他办法?(我是,所以这不是问题)
我正在看中的高级示例(但我可以使用另一个库)。最后,示例说,//执行添加和检查文章的操作
,我会在这里调用main()
我粘贴了下面的高级示例,以供将来参考
写出来帮助我回答了自己的问题
main()
将读入环境变量,然后调用类似于doBackup(client\u id,region)
的函数。我的测试将模拟端点,然后调用doBackup(client\u id,region)
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
}