使用路径变量测试 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中文网其他相关文章!