網頁

2021/12/8

Golang chi router REST API 測試範例

Golang chi router REST API的測試範例。


範例環境

  • Go 1.17
  • chi v5


範例測試一個帶路徑參數的API GET| /employee/{id}

受測程式

GET| /employee/{id}的回應內容為路徑參數id

main.go

package main

import (
    "log"
    "net/http"

    "github.com/go-chi/chi/v5"
)

func main() {
    http.ListenAndServe(":8080", NewRouter()) // start serve
}

func NewRouter() http.Handler {
    router := chi.NewRouter() // create chi router
    router.Get("/employee/{id}", HandHello()) // path param name "id"
    return router
}

func HandHello() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        id := chi.URLParam(r, "id") // get path param {id}

        log.Printf("path=%s\n", r.URL.Path)
        log.Printf("id=%s", id)

        w.Write([]byte(id))
    }
}


測試程式

TestHello()測試GET| /employee/{id}

main_test.go

package main

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

func TestHello(t *testing.T) {

    srv := NewRouter()                                    // create chi router
    r := httptest.NewRequest("GET", "/employee/123", nil) // 建立一個http.Request請求
    w := httptest.NewRecorder()                           // 建立一個ResponseRecorder其實作http.ResponseWriter,用來記錄response狀態

    srv.ServeHTTP(w, r) // 傳入ReponseWriter及Request

    expectedStatus := http.StatusOK // 預期HTTP回應狀態碼
    expectedContent := "123"        // 預期回應內容

    statusCode := w.Result().StatusCode // 實際HTTP回應狀態碼
    content := w.Body.String()          // 實際HTTP回應內容
    defer w.Result().Body.Close()

    if statusCode != expectedStatus {
        t.Errorf("expected code == %d, but %d", expectedStatus, statusCode)
    }
    if content != expectedContent {
        t.Errorf("expected content == %s, but %s", expectedContent, content)
    }

}


執行測試

在專案根目錄以命令列執行go test -v測試的結果如下。

~/../go-demo$ go test -v
=== RUN   TestHello
2021/12/08 21:49:56 path=/employee/123
2021/12/08 21:49:56 id=123
--- PASS: TestHello (0.00s)
PASS
ok      abc.com/demo    0.123s

參考github


沒有留言:

張貼留言