假设我正在测试一个调用 Web 服务的功能,并且该服务被模拟为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)) }}如何断言服务器是使用正确的 url 调用的,/foo如果使用错误的 url 调用或根本没有调用它,则测试失败?
1 回答
慕标5832272
TA贡献1966条经验 获得超4个赞
你可以这样做:
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 关注
- 82 浏览
添加回答
举报
0/150
提交
取消