我想编写一个测试用例来验证我的参数解析器函数。以下是我模拟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)
}
我的Web服务器使用github.com/gorilla/mux作为路由
router := mux.NewRouter()
router.HandleFunc("/search/{query_type}", searchApiService.Search).Methods("GET")
但在我的测试案例中,我无法从模拟{query_type}
获得http.request
func (api WebService) searchRequest(req *http.Request){
// skip ....
vars := mux.Vars(req)
queryType := vars["query_type"]
logger.Infof("queryType:%v", queryType)
//skip ....
}
如何在我的测试用例中获取mux的path参数?
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)
}