如何在 golang 中为我的测试用例正确创建模拟 http.request?

Posted

技术标签:

【中文标题】如何在 golang 中为我的测试用例正确创建模拟 http.request?【英文标题】:How to correctlly create mock http.request in golang for my test case? 【发布时间】:2019-03-30 00:13:10 【问题描述】:

我想写一个测试用例来验证我的参数解析器功能。 以下是我模拟 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 的路径参数?

【问题讨论】:

【参考方案1】:
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)

【讨论】:

改用httptest.NewRequest

以上是关于如何在 golang 中为我的测试用例正确创建模拟 http.request?的主要内容,如果未能解决你的问题,请参考以下文章