>  기사  >  백엔드 개발  >  단위 테스트를 위해 Chi 경로의 경로 변수에 액세스하는 방법은 무엇입니까?

단위 테스트를 위해 Chi 경로의 경로 변수에 액세스하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-27 07:33:29888검색

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

컨텍스트 종속 경로 변수를 사용하여 Chi 경로 테스트

경로 변수에 의존하는 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 경로의 경로 변수에 액세스하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.