網頁

2022/5/30

Golang mock http call response

Go單元測試時對http發送請求的API回應做mock。


事前要求

參考「Golang 發送請求」的Post(url string)


撰寫測試

建立測試程式main_test.go並新增TestPost()用來測試Post(url string)

利用httptest.NewServer()建立mock server來處理http.Post()的請求並回傳mock response內容為"hello"。然後呼叫httptest.Server.URL取得mock server的url取代原本真實的url路徑。

main_test.go

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestPost(t *testing.T) {
    // create mock target server
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("hello")) // mock response
    }))
    defer ts.Close() // shutdown mock server after test finished

    result := Post(ts.URL) // use mock target server url to replace real url
    if result != "hello" {
        t.Errorf("unexpected result=%v", result)
    }
}


執行測試

在專案根目錄輸入go test ./... -v結果如下:

~/../go-demo$ go test ./... -v
=== RUN   TestPost
--- PASS: TestPost (0.00s)
PASS
ok      abc.com/demo    0.345s


沒有留言:

張貼留言