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

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

How do I guarantee that the request happened correctly when mocking an API?

问题

假设我正在测试一个调用 Web 服务的功能,并且该服务使用 httptest.NewServer 进行模拟。

  1. func TestSomeFeature(t *testing.T) {
  2. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3. w.WriteHeader(200)
  4. }))
  5. SomeFeature(server.URL, "foo")
  6. }
  7. func SomeFeature(host, a string) {
  8. if a == "foo" {
  9. http.Get(fmt.Sprintf("%v/foo", host))
  10. }
  11. if a == "bar" {
  12. http.Get(fmt.Sprintf("%v/bar", host))
  13. }
  14. }

如何断言服务器是否使用正确的 URL /foo 进行调用,并在调用了错误的 URL 或者根本没有调用时失败测试呢?

英文:

Let's say I'm testing a feature that calls a web service, and that service is mocked with httptest.NewServer

  1. func TestSomeFeature(t *testing.T) {
  2. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3. w.WriteHeader(200)
  4. }))
  5. SomeFeature(server.URL, "foo")
  6. }
  7. func SomeFeature(host, a string) {
  8. if a == "foo" {
  9. http.Get(fmt.Sprintf("%v/foo", host))
  10. }
  11. if a == "bar" {
  12. http.Get(fmt.Sprintf("%v/bar", host))
  13. }
  14. }

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

你可以这样做:

  1. func TestSomeFeature(t *testing.T) {
  2. called := false
  3. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  4. // 断言 strings.Contains(r.RequestURI, "/foo") 为真
  5. called = true
  6. w.WriteHeader(200)
  7. }))
  8. SomeFeature(server.URL, "foo")
  9. // 断言 called 为真
  10. }
英文:

You can do it like this:

  1. func TestSomeFeature(t *testing.T) {
  2. called := false
  3. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  4. // assert that strings.Contains(r.RequestURI, "/foo") is true
  5. called = true
  6. w.WriteHeader(200)
  7. }))
  8. SomeFeature(server.URL, "foo")
  9. // assert that called is true
  10. }

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:

确定