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

how*_*wie 4 routes go

我想编写一个测试用例来验证我的参数解析器功能。以下是我模拟 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)
}
Run Code Online (Sandbox Code Playgroud)

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

router := mux.NewRouter()

router.HandleFunc("/search/{query_type}", searchApiService.Search).Methods("GET")

Run Code Online (Sandbox Code Playgroud)

但在我的测试用例中我无法{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 ....
}
Run Code Online (Sandbox Code Playgroud)

如何在我的测试用例中获取 mux 的路径参数?

小智 5

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 请改用“httptest.NewRequest”。 (2认同)