」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中使用即時請求測試 HTTP 伺服器?

如何在 Go 中使用即時請求測試 HTTP 伺服器?

發佈於2024-11-09
瀏覽:196

How to Test HTTP Servers with Live Requests in Go?

在Go 中使用即時請求測試HTTP 伺服器

獨立的單元測試處理程序至關重要,但可能忽略路由和其他中間件的影響。對於全面的測試,請考慮使用“實時伺服器”方法。

使用 httptest.Server 進行即時伺服器測試

net/http/httptest.Server 類型有助於即時伺服器測試。它使用提供的處理程序(在本例中為 Gorilla mux 路由器)建立一個伺服器。這是一個例子:

func TestIndex(t *testing.T) {
  // Create server using the router initialized elsewhere.
  ts := httptest.NewServer(router)
  defer ts.Close()

  newreq := func(method, url string, body io.Reader) *http.Request {
    r, err := http.NewRequest(method, url, body)
    if err != nil {
        t.Fatal(err)
    }
    return r
  }

  tests := []struct {
    name string
    r    *http.Request
  }{
    // Test GET and POST requests.
    {name: "1: testing get", r: newreq("GET", ts.URL "/", nil)},
    {name: "2: testing post", r: newreq("POST", ts.URL "/", nil)}, // reader argument required for POST
  }
  for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        resp, err := http.DefaultClient.Do(tt.r)
        defer resp.Body.Close()
        if err != nil {
            t.Fatal(err)
        }
        // check for expected response here.
    })
  }
}

請注意,httptest.Server 可用於測試滿足 http.Handler 介面的任何處理程序,而不僅僅是 Gorilla mux。

注意事項

雖然即時伺服器測試提供了更真實的測試,但它也比單元測試更慢且更消耗資源。考慮將單元測試和整合測試結合以實現全面的測試策略。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3