Go中的单元测试

huangapple go评论71阅读模式
英文:

Unit testing in go

问题

我想测试API函数,但参数出了问题。

func SetAPIConfigHandler(w http.ResponseWriter, r *http.Request) {
    var apiConfig model.Configuration
    err := json.NewDecoder(r.Body).Decode(&apiConfig)
    if err != nil {
        responderror(w, http.StatusBadRequest, err.Error())
    } else {
        utils.Domain = apiConfig.Domain
        utils.BaseURL = apiConfig.BaseURL
        utils.Tenant = apiConfig.Tenant
        respondJSON(w, http.StatusOK, apiConfig)
    }
}
英文:

I want to test the API function but arguments give the problem.

 func SetAPIConfigHandler(w http.ResponseWriter, r *http.Request) {
	var apiConfig model.Configuration
	err := json.NewDecoder(r.Body).Decode(&apiConfig)
	if err != nil {
		responderror(w, http.StatusBadRequest, err.Error())
	} else {
		utils.Domain = apiConfig.Domain
		utils.BaseURL = apiConfig.BaseURL
		utils.Tenant = apiConfig.Tenant
		respondJSON(w, http.StatusOK, apiConfig)
	}
}

答案1

得分: 2

你可以使用httptest进行测试,类似于这样:

req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
SetAPIConfigHandler(w, req)

resp := w.Result()
body, _ := io.ReadAll(resp.Body)

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))

请注意,这是一个示例代码,用于演示如何使用httptest进行测试。你需要根据自己的实际情况进行相应的修改和调整。

英文:

You can test it using httptest, something like this:

	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	w := httptest.NewRecorder()
	SetAPIConfigHandler(w, req)

	resp := w.Result()
	body, _ := io.ReadAll(resp.Body)

	fmt.Println(resp.StatusCode)
	fmt.Println(resp.Header.Get("Content-Type"))
	fmt.Println(string(body))

huangapple
  • 本文由 发表于 2021年6月17日 16:37:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/68015802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定