dswg47377
2019-03-30 00:13
浏览 244
已采纳

如何在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?

图片转代码服务由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.Fatal(err)
} 
 logger.Infof(  “%v”,req)
返回api.searchRequest(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)
      callfun(w,r)
    }
    
    打赏 评论

相关推荐 更多相似问题