英文:
How do I guarantee that the request happened correctly when mocking an API?
问题
假设我正在测试一个调用 Web 服务的功能,并且该服务使用 httptest.NewServer
进行模拟。
func 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 或者根本没有调用时失败测试呢?
英文:
Let's say I'm testing a feature that calls a web service, and that service is mocked with httptest.NewServer
func 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))
}
}
How do I assert that the server was called with the right url /foo
and fail the test if it was called with the wrong url or not called at all?
答案1
得分: 3
你可以这样做:
func TestSomeFeature(t *testing.T) {
called := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 断言 strings.Contains(r.RequestURI, "/foo") 为真
called = true
w.WriteHeader(200)
}))
SomeFeature(server.URL, "foo")
// 断言 called 为真
}
英文:
You can do it like this:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论