“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何在 golang 中为我的测试用例正确创建模拟 http.request?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
我想编写一个测试用例来验证我的参数解析器功能。 以下是我模拟 http.request 的示例代码
rawurl := "http://localhost/search/content?query=test"
func createsearchrequest(rawurl string) searchrequest {
api := newwebservice()
req, err := http.newrequest("post", rawurl, nil)
if err != nil {
logger.fatal(err)
}
logger.infof("%v", req)
return api.searchrequest(req)
}
我的网络服务器使用 github.com/gorilla/mux 作为路由
router := mux.newrouter()
router.handlefunc("/search/{query_type}", searchapiservice.search).methods("get")
但在我的测试用例中,我无法从模拟 http.request 获取 {query_type}
func (api WebService) searchRequest(req *http.Request){
// skip ....
vars := mux.Vars(req)
queryType := vars["query_type"]
logger.Infof("queryType:%v", queryType)
//skip ....
}
如何在测试用例中获取 mux 的路径参数?
解决方案
func TestMaincaller(t *testing.T) {
r,_ := http.NewRequest("GET", "hello/1", nil)
w := httptest.NewRecorder()
//create a map of variable and set it into mux
vars := map[string]string{
"parameter_name": "parametervalue",
}
r = mux.SetURLVars(r, vars)
callfun(w,r)
}本篇关于《如何在 golang 中为我的测试用例正确创建模拟 http.request?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
