为什么运行 mux API 测试时响应正文为空?
时间:2024-03-16
浏览: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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
