溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Golang?httptest包測(cè)試如何使用

發(fā)布時(shí)間:2023-03-15 11:27:17 來源:億速云 閱讀:86 作者:iii 欄目:開發(fā)技術(shù)

這篇“Golang httptest包測(cè)試如何使用”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Golang httptest包測(cè)試如何使用”文章吧。

測(cè)試http服務(wù)端處理器

下面通過示例介紹http server的測(cè)試。首先看http服務(wù)程序,把請(qǐng)求字符串轉(zhuǎn)為大寫:

package main
import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "strings"
)
// Req: http://localhost:1234/upper?word=abc
// Res: ABC
func upperCaseHandler(w http.ResponseWriter, r *http.Request) {
    query, err := url.ParseQuery(r.URL.RawQuery)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        fmt.Fprintf(w, "invalid request")
        return
    }
    word := query.Get("word")
    if len(word) == 0 {
        w.WriteHeader(http.StatusBadRequest)
        fmt.Fprintf(w, "missing word")
        return
    }
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, strings.ToUpper(word))
}
func main() {
    http.HandleFunc("/upper", upperCaseHandler)
    log.Fatal(http.ListenAndServe(":1234", nil))
}

現(xiàn)在想測(cè)試http server使用的upperCaseHandler邏輯,我們需要準(zhǔn)備兩方面:

  • 使用httptest.NewRequest暴露的函數(shù)創(chuàng)建http.Request對(duì)象,NewRequest返回Request, 可以傳給http.Handler進(jìn)行測(cè)試.

  • 使用httptest.NewRecorder函數(shù)創(chuàng)建http.ResponseWriter,返回httptest.ResponseRecorder。ResponseRecorder是

http.ResponseWriter 的實(shí)現(xiàn),它記錄變化為了后面測(cè)試檢查.

httptest.ResponseRecorder

httptest.ResponseRecorder是 http.ResponseWriter 的實(shí)現(xiàn),可以傳給http server handle,記錄所有處理并寫回響應(yīng)的數(shù)據(jù),下面測(cè)試程序可以看到其如何實(shí)現(xiàn):

package main
import (
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"
)
func TestUpperCaseHandler(t *testing.T) {
    req := httptest.NewRequest(http.MethodGet, "/upper?word=abc", nil)
    w := httptest.NewRecorder()
    upperCaseHandler(w, req)
    res := w.Result()
    defer res.Body.Close()
    data, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Errorf("expected error to be nil got %v", err)
    }
    if string(data) != "ABC" {
        t.Errorf("expected ABC got %v", string(data))
    }
}

上面示例中首先定義請(qǐng)求和響應(yīng),然后傳入處理器進(jìn)行測(cè)試。然后檢查ResponseRecorder的Result方法輸出:

func (rw *ResponseRecorder) Result() *http.Response

Result返回處理器生成的響應(yīng)。返回相應(yīng)至少有StatusCode, Header, Body, 以及可選其他內(nèi)容,未來可能會(huì)填充更多字段,所以調(diào)用者在測(cè)試中不應(yīng)該深度比較相等。

測(cè)試HTTP客戶端

測(cè)試服務(wù)端處理器相對(duì)容易,特別當(dāng)測(cè)試處理器邏輯時(shí),僅需要在測(cè)試中模擬http.ResponseWriter 和 http.Request對(duì)象。對(duì)于HTTP客戶端測(cè)試,情況稍晚有點(diǎn)復(fù)雜。原因是有時(shí)不容易模擬或復(fù)制整個(gè)HTTP Server,請(qǐng)看下面示例:

package main
import (
    "io/ioutil"
    "net/http"
    "github.com/pkg/errors"
)
type Client struct {
    url string
}
func NewClient(url string) Client {
    return Client{url}
}
func (c Client) UpperCase(word string) (string, error) {
    res, err := http.Get(c.url + "/upper?word=" + word)
    if err != nil {
        return "", errors.Wrap(err, "unable to complete Get request")
    }
    defer res.Body.Close()
    out, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return "", errors.Wrap(err, "unable to read response data")
    }
    return string(out), nil
}

client需要url,表示遠(yuǎn)程服務(wù)端基地址。然后調(diào)用/upper,帶上輸入單詞,最后返回結(jié)果字符串給調(diào)用者,如果調(diào)用不成功還返回錯(cuò)誤對(duì)象。為了測(cè)試這段代碼,需要模擬整個(gè)http服務(wù)端邏輯,或至少是響應(yīng)請(qǐng)求路徑:/upper。使用httptest包可以模擬整個(gè)http 服務(wù),通過初始化本地服務(wù),監(jiān)聽回環(huán)地址并返回你想要的任何內(nèi)容。

使用 httptest.Server

通過調(diào)用httptest.NewServer函數(shù)生成我們想要的 httptest.Server。表示http服務(wù),監(jiān)聽回環(huán)地址及可選的端口號(hào),用于實(shí)現(xiàn)端到端HTTP測(cè)試。

func NewServer(handler http.Handler) *Server

NewServer 啟動(dòng)并返回新的HTTP服務(wù),調(diào)用者使用完成后應(yīng)該調(diào)用Close方法結(jié)束服務(wù)。下面通過示例進(jìn)行解釋:

package main
import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)
func TestClientUpperCase(t *testing.T) {
    expected := "dummy data"
    svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, expected)
    }))
    defer svr.Close()
    c := NewClient(svr.URL)
    res, err := c.UpperCase("anything")
    if err != nil {
        t.Errorf("expected err to be nil got %v", err)
    }
    // res: expected\r\n
    // due to the http protocol cleanup response
    res = strings.TrimSpace(res)
    if res != expected {
        t.Errorf("expected res to be %s got %s", expected, res)
    }
}

上面示例中使用httptest.NewServer函數(shù)創(chuàng)建了模擬http服務(wù)器,給它傳入自定義模擬處理器,總是返回相同的數(shù)據(jù)。并使用服務(wù)端url作為客戶端請(qǐng)求url,從而模擬并讓服務(wù)端返回任何我們想測(cè)試的內(nèi)容。

當(dāng)然我們可以修改處理器,讓其返回我們期望的邏輯:

func TestClientUpperCase(t *testing.T) {
	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		query, err := url.ParseQuery(r.URL.RawQuery)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprintf(w, "invalid request")
			return
		}
		word := query.Get("word")
		if len(word) > 0 {
			fmt.Fprintf(w, strings.ToUpper(word))
		} else {
			fmt.Fprintf(w, "no input")
		}
	}))
	defer svr.Close()
	expected := "ANYTHING"
	c := NewClient(svr.URL)
	res, err := c.UpperCase("anything")
	if err != nil {
		t.Errorf("expected err to be nil got %v", err)
	}
	// res: expected\r\n
	// due to the http protocol cleanup response
	res = strings.TrimSpace(res)
	if res != expected {
		t.Errorf("expected res to be %s got %s", expected, res)
	}
}

以上就是關(guān)于“Golang httptest包測(cè)試如何使用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI