Home > Backend Development > Golang > How to Access Path Variables in Chi Routes for Unit Tests?

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

DDD
Release: 2024-10-27 07:33:29
Original
986 people have browsed it

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

Testing Chi Routes with Context-Dependent Path Variables

When testing Chi routes that rely on path variables, it's crucial to mimic the access to these variables in tests. Initially, you may encounter an "Unprocessable Entity" error due to the path variable not being available to the context accessed in the test.

Contextualizing the Tests

To resolve this issue, manually add the path parameters to the request context before executing the handler under test. Here's an example:

<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>
Copy after login

This modification allows the test to access the path variable through the context, resolving the "Unprocessable Entity" error.

The above is the detailed content of How to Access Path Variables in Chi Routes for Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template