gpt4 book ai didi

go - 使用http.NewRequest进行测试时,为什么我的请求URL解析不正确?

转载 作者:行者123 更新时间:2023-12-01 22:10:47 25 4
gpt4 key购买 nike

当我使用curl测试我的/ health /端点时,一切都按预期工作:curl localhost:8080/health/my_id返回my_id
但是,当我运行测试时,处理程序无法从参数中提取ID。
我应该如何从测试中构建查询以实现这一目标?
HealthTest

 12 func TestHealth(t *testing.T) {
13
14 // Initialize a new httptest.ResponseRecorder.
15 rr := httptest.NewRecorder()
16
17 // Initialize a new dummy http.Request.
18 r, err := http.NewRequest(http.MethodGet, "/health/my_id", nil)
19 if err != nil {
20 t.Fatal(err)
21 }
22
23 // Call the handler function, passing in the
24 // httptest.ResponseRecorder and http.Request.
25 handler.HandleHealth(rr, r)
26
27 // Call the Result() method on the http.ResponseRecorder to get the
28 // http.Response generated by the handler.
29 rs := rr.Result()
30
31 // We can then examine the http.Response to check that the status code // written by the handler was 200.
32 if rs.StatusCode != http.StatusOK {
33 t.Errorf("want %d; got %d", http.StatusOK, rs.StatusCode)
34 }
35
36 // And we can check that the response body written by the handler
37 defer rs.Body.Close()
38 body, err := ioutil.ReadAll(rs.Body)
39 if err != nil {
40 t.Fatal(err)
41 }
42
43 want := "my_id"
44 got := string(body)
45 if got != want {
46 t.Errorf("want body to equal %q. Got: %q", want, got)
47 }
48 }
运行该测试会导致:
internal/handler/health/handler_test.go|46| want body to equal "my_id". Got: ""
HealthHandlers
   23 func (h *Handler) HandleHealth(w http.ResponseWriter, r *http.Request) {
24 id := chi.URLParam(r, "id")
25 log.Println("ID: ", id)
26 render.PlainText(w, r, id)
27 }
28

29 func RegisterRoutes(router *chi.Mux, handler *Handler) {
30 router.Get("/health/{id}", handler.HandleHealth)
31 }

最佳答案

chi库是处理通配符URL的库。但是,您可以通过直接调用HandleHealth绕过测试中的chi。
如果要让chi针对RegisterRoutes方法中提供的通配符处理请求,则显然需要在测试中实际调用RegisterRoutes
这样做需要稍微更改测试结构。而不是:

    handler.HandleHealth(rr, r)
您将需要以下内容:
    chi := chi.NewMux()
RegisterRoutes(chi, handler)
chi.ServeHTTP(rr, r)

关于go - 使用http.NewRequest进行测试时,为什么我的请求URL解析不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63935582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com