如何在golang中为我的测试用例正确创建模拟http.request?
I want to write a test case to verify my parameter parser function. The following is my sample code to mock a 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)
}
My web server use github.com/gorilla/mux as route
router := mux.NewRouter()
router.HandleFunc("/search/{query_type}", searchApiService.Search).Methods("GET")
But in my test case I cannot get {query_type}
from mock http.request
func (api WebService) searchRequest(req *http.Request){
// skip ....
vars := mux.Vars(req)
queryType := vars["query_type"]
logger.Infof("queryType:%v", queryType)
//skip ....
}
How can I get mux's path parameter in my test case?
我想编写一个测试用例来验证我的参数解析器功能。 以下是我的示例代码,用于模拟 http.request p>
rawUrl:=“ http:// localhost / search / content?query = test”
func createSearchRequest(rawUrl字符串)SearchRequest {
api: = NewWebService()
req,err:= http.NewRequest(“ POST”,rawUrl,nil)
if err!= nil {
logger.Fatal(err)
}
logger.Infof( “%v”,req)
返回api.searchRequest(req)
}
code> pre>
我的Web服务器使用 github.com/gorilla/mux strong>作为路由 p>
router:= mux.NewRouter()
router.HandleFunc(“ / search / {query_type}”,searchApiService.Search)。方法 (“ GET”)
code> pre>
但是在我的测试案例中,我无法从模拟 http.request中获得 {query_type} code> code> p>
func(api WebService)searchRequest(req * http.Request){
//跳过....
vars:=多路复用器。 Vars(req)
queryType:= vars [“ query_ty pe“]
logger.Infof(” queryType:%v“,queryType)
//跳过....
}
code> pre>
如何 我可以在测试用例中获取多路复用器的path参数吗? p>
div>
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)
}