Home  >  Article  >  Backend Development  >  How to Test Go-Chi Routes with Path Variables Using httptest.NewRouteContext?

How to Test Go-Chi Routes with Path Variables Using httptest.NewRouteContext?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 11:48:02298browse

How to Test Go-Chi Routes with Path Variables Using httptest.NewRouteContext?

Testing Chi Routes with Path Variables

When testing Go-Chi routes with path variables, you may encounter errors related to missing path variable values. This can occur because the path variables are not automatically added to the request context when using httptest.NewRequest.

To resolve this issue, add the path variables manually to the request context using the httptest.NewRouteContext function. Here's an example:

<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>

The above is the detailed content of How to Test Go-Chi Routes with Path Variables Using httptest.NewRouteContext?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn