第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何斷言請求在同時模擬 API 時發(fā)生?

如何斷言請求在同時模擬 API 時發(fā)生?

Go
慕田峪4524236 2022-10-17 10:23:40
main.gopackage mainimport (    "net/http")func SomeFeature(host, a string) {    if a == "foo" {        resp, err := http.Get(host + "/foo")    }    if a == "bar" {        resp, err := http.Get(host + "/baz"))    }    // baz is missing, the test should error!}main_test.gopackage mainimport (    "net/http"    "net/http/httptest"    "testing")func TestSomeFeature(t *testing.T) {    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        w.WriteHeader(200)    }))    testCases := []struct {        name     string        variable string    }{        {            name:     "test 1",            variable: "foo",        },        {            name:     "test 2",            variable: "bar",        },        {            name:     "test 3",            variable: "baz",        },    }    for _, tc := range testCases {        tc := tc        t.Run(tc.name, func(t *testing.T) {            t.Parallel()            SomeFeature(server.URL, tc.variable)            // assert that the http call happened somehow?        })    }}去游樂場:https ://go.dev/play/p/EFanSSzgnbk如何斷言每個測試用例都向模擬服務(wù)器發(fā)送請求?如何斷言未發(fā)送請求?同時保持測試并行/并發(fā)?
查看完整描述

1 回答

?
阿波羅的戰(zhàn)車

TA貢獻(xiàn)1862條經(jīng)驗 獲得超6個贊

您可以為每個測試用例創(chuàng)建一個新服務(wù)器。


或者您可以使用通道,特別是通道映射,其中鍵是測試用例的標(biāo)識符,例如


getChans := map[string]chan struct{}{}

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    key := strings.Split(r.URL.Path, "/")[1] // extract channel key from path

    go func() { getChans[key] <- struct{}{} }()


    w.WriteHeader(200)

}))

向測試用例添加通道鍵字段。這將被添加到主機(jī)的 URL 中,然后處理程序?qū)⑻崛∶荑€,如上所示,以獲取正確的頻道。還要添加一個字段來指示是否http.Get應(yīng)該調(diào)用:


testCases := []struct {

    name      string

    chkey     string

    variable  string

    shouldGet bool

}{

    {

        name:      "test 1",

        chkey:     "key1"

        variable:  "foo",

        shouldGet: true,

    },

    // ...

}

在運(yùn)行測試用例之前,將特定于測試用例的通道添加到地圖中:


getChans[tc.chkey] = make(chan struct{})

然后使用測試用例中的通道鍵字段作為主機(jī) URL 路徑的一部分:


err := SomeFeature(server.URL+"/"+tc.chkey, tc.variable)

if err != nil {

    t.Error("SomeFeature should not error")

}

并檢查是否http.Get被稱為使用select一些可接受的超時:


select {

case <-getChans[tc.chkey]:

    if !tc.shouldGet {

        t.Error(tc.name + " get called")

    }

case <-time.Tick(3 * time.Second):

    if tc.shouldGet {

        t.Error(tc.name + " get not called")

    }

}

https://go.dev/play/p/7By3ArkbI_o


查看完整回答
反對 回復(fù) 2022-10-17
  • 1 回答
  • 0 關(guān)注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號