当模拟一个 API 请求时,如何确保请求正确地发生呢?

huangapple go评论68阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2021年11月24日 05:15:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/70087909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定