假設(shè)我正在測試一個(gè)調(diào)用 Web 服務(wù)的功能,并且該服務(wù)被模擬為httptest.NewServerfunc TestSomeFeature(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })) SomeFeature(server.URL, "foo")}func SomeFeature(host, a string) { if a == "foo" { http.Get(fmt.Sprintf("%v/foo", host)) } if a == "bar" { http.Get(fmt.Sprintf("%v/bar", host)) }}如何斷言服務(wù)器是使用正確的 url 調(diào)用的,/foo如果使用錯(cuò)誤的 url 調(diào)用或根本沒有調(diào)用它,則測試失???
1 回答

慕標(biāo)5832272
TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以這樣做:
func TestSomeFeature(t *testing.T) {
called := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// assert that strings.Contains(r.RequestURI, "/foo") is true
called = true
w.WriteHeader(200)
}))
SomeFeature(server.URL, "foo")
// assert that called is true
}
- 1 回答
- 0 關(guān)注
- 102 瀏覽
添加回答
舉報(bào)
0/150
提交
取消