我有类似下面的一组请求处理程序:如何测试Golang中的http请求处理程序?
func GetProductsHandler(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
products := db.GetProducts()
// ...
// return products as JSON array
}
如何测试他们以正确的方式?我应该将模拟的ResponseWriter和Request对象发送给函数并查看结果吗?
是否有工具可以在Go中模拟请求和响应对象以简化流程,而无需在测试之前启动服务器?
你的意思是['httptest' package](https://golang.org/pkg/net/http/httptest/)? – JimB
'http.Request'和'http.Response'都是简单的和“完全导出”的类型,所以只需将它们设置为任何你想要或需要的。不需要工具或“嘲笑”。 – Volker
https://golang.org/pkg/net/http/httptest/#example_ResponseRecorder – dm03514