为什么运行 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亮相工信部公告,外观配置大升级
- 上一篇
- 比亚迪新款腾势N7亮相工信部公告,外观配置大升级
- 下一篇
- go-testfixtures Fixtures.Load() 返回校验和错误
-
- Golang · Go问答 | 1天前 | goroutine · HTTP · Context · 超时控制 · Go问答 · WithTimeout Go问答 context取消 QueryContext HTTP请求取消 goroutine退出
- Go HTTP 请求取消后任务会自动停吗:context 传递、超时和资源释放
- 120浏览 收藏
-
- Golang · Go问答 | 1天前 | sync.Pool · reset · 对象复用 · Go问答 · 线上排查 · Go sync.Pool Go问答 sync.Pool串数据 Reset清理 对象池复用
- Go sync.Pool 为什么会串数据:Reset 和 Put 的顺序怎么定
- 342浏览 收藏
-
- Golang · Go问答 | 2天前 | [] · []
- Go time.After 写在循环里会泄漏吗:定时器堆积、Stop 和 NewTimer 复用怎么判断
- 181浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ljg-skills
- ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
- 4401次使用
-
- MELO音乐
- MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
- 4070次使用
-
- UniScribe
- UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
- 4053次使用
-
- 剧云
- 剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
- 4238次使用
-
- 万象有声
- 万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
- 4209次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 从不同的 go 例程将数据写入同一通道无需等待组即可正常工作
- 2024-04-29 501浏览
-
- Golang rsa-oaep解密失败,前端使用webcrypto
- 2024-04-26 501浏览
-
- 如何从用户输入以惰性方式初始化包的全局变量?
- 2024-04-24 501浏览

