为什么运行 mux API 测试时响应正文为空?
来源:stackoverflow
时间:2024-03-16 21:48:31 495浏览 收藏
在编写 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学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习