【问题标题】:How to correctlly create mock http.request in golang for my test case?如何在 golang 中为我的测试用例正确创建模拟 http.request?
【发布时间】: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 的路径参数?

【问题讨论】:

    标签: go routes


    【解决方案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
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多