首页 >后端开发 >Golang >如何访问 Chi Rous 中的路径变量进行单元测试?

如何访问 Chi Rous 中的路径变量进行单元测试?

DDD
DDD原创
2024-10-27 07:33:29987浏览

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 Rous 中的路径变量进行单元测试?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn