1 回答

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
- 1 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報