首頁 > 後端開發 > Golang > 主體

如何存取 Chi Rous 中的路徑變數進行單元測試?

DDD
發布: 2024-10-27 07:33:29
原創
896 人瀏覽過

How to Access Path Variables in Chi Routes for Unit Tests?

使用上下文相關的路徑變數測試 Chi 路由

測試依賴路徑變數的 Chi 路由時,在測試中模擬對這些變數的存取至關重要。最初,由於路徑變數無法用於測試中存取的上下文,您可能會遇到「無法處理的實體」錯誤。

上下文化測試

要解決此問題,請手動添加在執行被測試的處理程序之前,請求上下文的路徑參數。以下是一個範例:

<code class="go">package main

import (
    "context"
    "fmt"
    "net/http"
    "net/http/httptest"
    "testing"

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

type ctxKey struct {
    name string
}

func TestGetArticleID(t *testing.T) {
    tests := []struct {
        name           string
        rec            *httptest.ResponseRecorder
        req            *http.Request
        expectedBody   string
        expectedHeader string
    }{
        {
            name:         "OK_1",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("GET", "/articles/1", nil),
            expectedBody: `article ID:1`,
        },
        {
            name:         "OK_100",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("GET", "/articles/100", nil),
            expectedBody: `article ID:100`,
        },
        {
            name:         "BAD_REQUEST",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("PUT", "/articles/bad", nil),
            expectedBody: fmt.Sprintf("%s\n", http.StatusText(http.StatusBadRequest)),
        },
    }

    for _, test := range tests {
        t.Run(test.name, func(t *testing.T) {
            // Manually add the path variable to the request context
            rctx := chi.NewRouteContext()
            rctx.URLParams.Add("articleID", test.req.URL.Path[len("/articles/"):])
            test.req = test.req.WithContext(context.WithValue(test.req.Context(), chi.RouteCtxKey, rctx))

            ArticleCtx(http.HandlerFunc(GetArticleID)).ServeHTTP(test.rec, test.req)

            if test.expectedBody != test.rec.Body.String() {
                t.Errorf("Got: \t\t%s\n\tExpected: \t%s\n", test.rec.Body.String(), test.expectedBody)
            }
        })
    }
}</code>
登入後複製

此修改允許測試透過上下文存取路徑變量,解決「無法處理的實體」錯誤。

以上是如何存取 Chi Rous 中的路徑變數進行單元測試?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!