2019-03-30 00:13
浏览 342


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.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?

图片转代码服务由CSDN问答提供 功能建议

我想编写一个测试用例来验证我的参数解析器功能。 以下是我的示例代码,用于模拟 http.request

  rawUrl:=“ http:// localhost / search / content?query = test” 
func createSearchRequest(rawUrl字符串)SearchRequest {
 api:  = NewWebService()
 req,err:= http.NewRequest(“ POST”,rawUrl,nil)
 if err!= nil {
 logger.Infof(  “%v”,req)

我的Web服务器使用 github.com/gorilla/mux 作为路由

  router:= mux.NewRouter()
router.HandleFunc(“ / search / {query_type}”,searchApiService.Search)。方法 (“ GET”)

但是在我的测试案例中,我无法从模拟 http.request中获得 {query_type}

  func(api WebService)searchRequest(req * http.Request){
 vars:=多路复用器。  Vars(req)
 queryType:= vars [“ query_ty  pe“] 
 logger.Infof(” queryType:%v“,queryType)

如何 我可以在测试用例中获取多路复用器的path参数吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongyu5482 2019-03-30 07:48
    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)
    解决 无用
    打赏 举报

相关推荐 更多相似问题