当我使用 http.NewRequest 进行测试时,为什么我的请求 URL 解析不正确?
时间:2024-04-14
浏览:188
作者:佚名
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《当我使用 http.NewRequest 进行测试时,为什么我的请求 URL 解析不正确?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容
当我使用curl测试我的/health/端点时,一切都按预期工作:
curl 本地主机:8080/health/my_id 返回 my_id。
但是当我运行测试时,处理程序无法从参数中提取 id。 我应该如何从测试中构造查询来实现这一目标?
健康测试
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: ""
健康处理程序
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)
终于介绍完啦!小伙伴们,这篇关于《当我使用 http.NewRequest 进行测试时,为什么我的请求 URL 解析不正确?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
