亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Go 的 http 測試模擬多個不同的 HTTP 響應?

如何使用 Go 的 http 測試模擬多個不同的 HTTP 響應?

Go
LEATH 2022-09-26 15:31:39
我已經創建了一些Go函數,這些函數對互聯網上的服務進行HTTP GET調用并解析結果。我現在正在為這些函數編寫測試用例。在我的測試用例中,我使用 go 包來模擬對這些外部服務的調用。以下是我的代碼。為簡潔起見,有意刪除了錯誤檢查。這是游樂場。httptestpackage mainimport (    "fmt"    "io"    "context"    "net/http"    "net/http/httptest")func handlerResponse() http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        w.WriteHeader(http.StatusOK)        w.Write([]byte(`{"A":"B"}`))    })}func buildMyRequest(ctx context.Context, url string) *http.Request {    request, _ := http.NewRequestWithContext(ctx, "GET", url, nil)    return request}func myPrint(response *http.Response) {    b := make([]byte, 60000)    for {        _, err := response.Body.Read(b)        if err == io.EOF {            break        }    }    fmt.Println(string(b))}func main() {    srv := httptest.NewServer(handlerResponse())                client := http.Client{}    myResponse1, _ := client.Do(buildMyRequest(context.Background(), srv.URL))    fmt.Println("myResponse1:")    myPrint(myResponse1)        myResponse2, _ := client.Do(buildMyRequest(context.Background(), srv.URL))    fmt.Println("myResponse2:")    myPrint(myResponse2)}這是它產生的輸出:myResponse1:{"A":"B"}myResponse2:{"A":"B"}如您所見,我已經創建了一些虛擬的HTTP響應數據,當您向發送HTTP請求時,它實際上會命中一個臨時的HTTP服務器,該服務器會用虛擬數據進行響應。涼!{"A":"B"}srv.URL當您將第二個 HTTP 請求發送到 時,它會再次使用相同的虛擬數據進行響應。但這就是我的問題出現的地方。我希望臨時HTTP服務器在第二次和第三次收到請求時返回一些不同的數據。srv.URL{"C":"D"}{"E":"F"}如何更改函數的第一行,以便服務器在后續 HTTP 調用中響應我所需的數據?main()
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

你可以使用一個黑客,如下(游樂場:這里)


package main


import (

    "fmt"

    "io"

    "context"

    "net/http"

    "net/http/httptest"

    "sync"

)



type responseWriter struct{

   resp map[int]string

   count int

   lock *sync.Mutex

}


func NewResponseWriter()*responseWriter{

   r := new(responseWriter)

   r.lock = new(sync.Mutex)

   r.resp = map[int]string{

    0: `{"E":"F"}`,

    1: `{"A":"B"}`,

    2: `{"C":"D"}`,

   }

   r.count = 0

   return r

}


func (r *responseWriter)GetResp()string{

   r.lock.Lock()

   defer r.lock.Unlock()

   r.count ++

   return r.resp[r.count%3]

}



func handlerResponse(rr *responseWriter) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        w.WriteHeader(http.StatusOK)

        w.Write([]byte(rr.GetResp()))

    })

}


func buildMyRequest(ctx context.Context, url string) *http.Request {

    request, _ := http.NewRequestWithContext(ctx, "GET", url, nil)

    return request

}



func myPrint(response *http.Response) {

    b := make([]byte, 60000)

    for {

        _, err := response.Body.Read(b)

        if err == io.EOF {

            break

        }

    }

    fmt.Println(string(b))

}


func main() {

        rr := NewResponseWriter()


    srv := httptest.NewServer(handlerResponse(rr))  

    client := http.Client{}


    myResponse1, err := client.Do(buildMyRequest(context.Background(), srv.URL))

    if err != nil{

       fmt.Println(err)

       return

    }

    

    defer myResponse1.Body.Close()

    fmt.Println("myResponse1:")

    myPrint(myResponse1)

    

    myResponse2, err := client.Do(buildMyRequest(context.Background(), srv.URL))

    if err != nil{

       fmt.Println(err)

       return

    }

    

    defer myResponse2.Body.Close()

    fmt.Println("myResponse2:")

    myPrint(myResponse2)

}


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號