后續問題:如何在模擬 API 時保證請求正確發生?
main.go
package main
import (
"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.go
package main
import (
"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?
})
}
}
- GO 游樂場:https : //go.dev/play/p/EFanSSzgnbk
- 如何斷言每個測驗用例都向模擬服務器發送請求?
- 如何斷言請求未發送?
在保持測驗并行/并發的同時?
uj5u.com熱心網友回復:
您可以為每個測驗用例創建一個新服務器。
或者您可以使用通道,特別是通道映射,其中鍵是測驗用例的識別符號,例如
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)
}))
向測驗用例添加一個通道鍵欄位。這將被添加到主機的 URL,然后處理程式將提取密鑰,如上所示,以獲得正確的頻道。還要添加一個欄位來指示是否http.Get應該呼叫:
testCases := []struct {
name string
chkey string
variable string
shouldGet bool
}{
{
name: "test 1",
chkey: "key1"
variable: "foo",
shouldGet: true,
},
// ...
}
在運行測驗用例之前,將特定于測驗用例的通道添加到映射中:
getChans[tc.chkey] = make(chan struct{})
然后使用測驗用例中的通道鍵欄位作為主機 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365984.html
