使用路徑變數測試Chi 路由
使用路徑變數測試Go-Chi 路由時,您可能會遇到與缺少路徑變數值相關的錯誤。發生這種情況是因為使用 httptest.NewRequest 時路徑變數不會自動新增到請求上下文。
要解決此問題,請使用 httptest.NewRouteContext 函數手動將路徑變數新增至請求上下文。這是一個範例:
<code class="go">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) { // Add path variables to the request context rctx := chi.NewRouteContext() rctx.URLParams.Add("articleID", "1") 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>
以上是如何使用 httptest.NewRouteContext 測試帶有路徑變數的 Go-Chi 路由?的詳細內容。更多資訊請關注PHP中文網其他相關文章!