測試依賴路徑變數的 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中文網其他相關文章!