为什么运行 mux API 测试时响应正文为空?
在编写 Go 测试时,运行 Mux API 测试时可能会遇到响应正文为空的情况。此问题通常是因为测试中未包含路由器,导致无法检测路径变量。解决方案是将路由器包含在测试中,通过调用路由器方法初始化处理程序,并从返回的 Mux 路由器实例中获取路径变量。此外,建议使用 `init` 函数进行一次性设置,以确保数据在测试运行前已初始化。通过这些修改,可以解决响应正文为空的问题,并确保测试能够正确验证 API 路由。
我正在尝试在 go 中构建和测试一个非常基本的 api,以便在遵循他们的教程后了解有关该语言的更多信息。 api 和定义的四个路由在 postman 和浏览器中工作,但是当尝试为任何路由编写测试时,responserecorder 没有主体,因此我无法验证它是否正确。
我按照此处的示例进行操作,它有效,但是当我更改路线时,没有响应。
这是我的 main.go
文件。
package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" ) // a person represents a user. type person struct { id string `json:"id,omitempty"` firstname string `json:"firstname,omitempty"` lastname string `json:"lastname,omitempty"` location *location `json:"location,omitempty"` } // a location represents a person's location. type location struct { city string `json:"city,omitempty"` country string `json:"country,omitempty"` } var people []person // getpersonendpoint returns an individual from the database. func getpersonendpoint(w http.responsewriter, req *http.request) { w.header().set("content-type", "application/json") params := mux.vars(req) for _, item := range people { if item.id == params["id"] { json.newencoder(w).encode(item) return } } json.newencoder(w).encode(&person{}) } // getpeopleendpoint returns all people from the database. func getpeopleendpoint(w http.responsewriter, req *http.request) { w.header().set("content-type", "application/json") json.newencoder(w).encode(people) } // createpersonendpoint creates a new person in the database. func createpersonendpoint(w http.responsewriter, req *http.request) { w.header().set("content-type", "application/json") params := mux.vars(req) var person person _ = json.newdecoder(req.body).decode(&person) person.id = params["id"] people = append(people, person) json.newencoder(w).encode(people) } // deletepersonendpoint deletes a person from the database. func deletepersonendpoint(w http.responsewriter, req *http.request) { w.header().set("content-type", "application/json") params := mux.vars(req) for index, item := range people { if item.id == params["id"] { people = append(people[:index], people[index+1:]...) break } } json.newencoder(w).encode(people) } // seeddata is just for this example and mimics a database in the 'people' variable. func seeddata() { people = append(people, person{id: "1", firstname: "john", lastname: "smith", location: &location{city: "london", country: "united kingdom"}}) people = append(people, person{id: "2", firstname: "john", lastname: "doe", location: &location{city: "new york", country: "united states of america"}}) } func main() { router := mux.newrouter() seeddata() router.handlefunc("/people", getpeopleendpoint).methods("get") router.handlefunc("/people/{id}", getpersonendpoint).methods("get") router.handlefunc("/people/{id}", createpersonendpoint).methods("post") router.handlefunc("/people/{id}", deletepersonendpoint).methods("delete") fmt.println("listening on http://localhost:12345") fmt.println("press 'ctrl + c' to stop server.") log.fatal(http.listenandserve(":12345", router)) }
这是我的 main_test.go
文件。
package main import ( "fmt" "net/http" "net/http/httptest" "testing" ) func testgetpeopleendpoint(t *testing.t) { req, err := http.newrequest("get", "/people", nil) if err != nil { t.fatal(err) } // we create a responserecorder (which satisfies http.responsewriter) to record the response. rr := httptest.newrecorder() handler := http.handlerfunc(getpeopleendpoint) // our handlers satisfy http.handler, so we can call their servehttp method // directly and pass in our request and responserecorder. handler.servehttp(rr, req) // trying to see here what is in the response. fmt.println(rr) fmt.println(rr.body.string()) // check the status code is what we expect. if status := rr.code; status != http.statusok { t.errorf("handler returned wrong status code: got %v want %v", status, http.statusok) } // check the response body is what we expect - commented out because it will fail because there is no body at the moment. // expected := `[{"id":"1","firstname":"john","lastname":"smith","location":{"city":"london","country":"united kingdom"}},{"id":"2","firstname":"john","lastname":"doe","location":{"city":"new york","country":"united states of america"}}]` // if rr.body.string() != expected { // t.errorf("handler returned unexpected body: got %v want %v", // rr.body.string(), expected) // } }
我知道我可能犯了一个初学者的错误,所以请怜悯我。我读过一些测试多路复用器的博客,但看不出我做错了什么。
预先感谢您的指导。
更新
将我的 seedata 调用移至 init()
解决了人员调用的正文为空的问题。
func init() { seeddata() }
但是,我现在在测试特定 id 时没有返回任何正文。
func testgetpersonendpoint(t *testing.t) { id := 1 path := fmt.sprintf("/people/%v", id) req, err := http.newrequest("get", path, nil) if err != nil { t.fatal(err) } // we create a responserecorder (which satisfies http.responsewriter) to record the response. rr := httptest.newrecorder() handler := http.handlerfunc(getpersonendpoint) // our handlers satisfy http.handler, so we can call their servehttp method // directly and pass in our request and responserecorder. handler.servehttp(rr, req) // check request is made correctly and responses. fmt.println(path) fmt.println(rr) fmt.println(req) fmt.println(handler) // expected response for id 1. expected := `{"id":"1","firstname":"john","lastname":"smith","location":{"city":"london","country":"united kingdom"}}` + "\n" if status := rr.code; status != http.statusok { message := fmt.sprintf("the test returned the wrong status code: got %v, but expected %v", status, http.statusok) t.fatal(message) } if rr.body.string() != expected { message := fmt.sprintf("the test returned the wrong data:\nfound: %v\nexpected: %v", rr.body.string(), expected) t.fatal(message) } }
将我的 seeddata 调用移至 init()
解决了人员调用的正文为空的问题。
func init() { seeddata() }
创建新的路由器实例解决了访问路由上变量的问题。
rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/people/{id}", GetPersonEndpoint) router.ServeHTTP(rr, req)
解决方案
我认为这是因为您的测试不包括路由器,因此未检测到路径变量。来,试试这个
// main.go func router() *mux.router { router := mux.newrouter() router.handlefunc("/people", getpeopleendpoint).methods("get") router.handlefunc("/people/{id}", getpersonendpoint).methods("get") router.handlefunc("/people/{id}", createpersonendpoint).methods("post") router.handlefunc("/people/{id}", deletepersonendpoint).methods("delete") return router }
在您的测试用例中,从路由器方法启动,如下所示
handler := router() // our handlers satisfy http.handler, so we can call their servehttp method // directly and pass in our request and responserecorder. handler.servehttp(rr, req)
现在,如果您尝试访问路径变量 id,它应该出现在 mux 返回的映射中,因为当您从 router() 返回的 mux router 实例初始化处理程序时,mux 注册了它
params := mux.vars(req) for index, item := range people { if item.id == params["id"] { people = append(people[:index], people[index+1:]...) break } }
也像您提到的那样,使用 init 函数进行一次性设置。
// main.go func init(){ SeedData() }
今天关于《为什么运行 mux API 测试时响应正文为空?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

- 上一篇
- 比亚迪新款腾势N7亮相工信部公告,外观配置大升级

- 下一篇
- go-testfixtures Fixtures.Load() 返回校验和错误
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 魔匠AI
- SEO摘要魔匠AI专注于高质量AI学术写作,已稳定运行6年。提供无限改稿、选题优化、大纲生成、多语言支持、真实参考文献、数据图表生成、查重降重等全流程服务,确保论文质量与隐私安全。适用于专科、本科、硕士学生及研究者,满足多语言学术需求。
- 20次使用
-
- PPTFake答辩PPT生成器
- PPTFake答辩PPT生成器,专为答辩准备设计,极致高效生成PPT与自述稿。智能解析内容,提供多样模板,数据可视化,贴心配套服务,灵活自主编辑,降低制作门槛,适用于各类答辩场景。
- 36次使用
-
- Lovart
- SEO摘要探索Lovart AI,这款专注于设计领域的AI智能体,通过多模态模型集成和智能任务拆解,实现全链路设计自动化。无论是品牌全案设计、广告与视频制作,还是文创内容创作,Lovart AI都能满足您的需求,提升设计效率,降低成本。
- 48次使用
-
- 美图AI抠图
- 美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
- 45次使用
-
- PetGPT
- SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
- 45次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览