当前位置:首页 > 文章列表 > Golang > Go问答 > 为什么运行 mux API 测试时响应正文为空?

为什么运行 mux API 测试时响应正文为空?

来源:stackoverflow 2024-03-16 21:48:31 0浏览 收藏

在编写 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学习网公众号!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
比亚迪新款腾势N7亮相工信部公告,外观配置大升级比亚迪新款腾势N7亮相工信部公告,外观配置大升级
上一篇
比亚迪新款腾势N7亮相工信部公告,外观配置大升级
go-testfixtures Fixtures.Load() 返回校验和错误
下一篇
go-testfixtures Fixtures.Load() 返回校验和错误
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • SEO标题魔匠AI:高质量学术写作平台,毕业论文生成与优化专家
    魔匠AI
    SEO摘要魔匠AI专注于高质量AI学术写作,已稳定运行6年。提供无限改稿、选题优化、大纲生成、多语言支持、真实参考文献、数据图表生成、查重降重等全流程服务,确保论文质量与隐私安全。适用于专科、本科、硕士学生及研究者,满足多语言学术需求。
    20次使用
  • PPTFake答辩PPT生成器:一键生成高效专业的答辩PPT
    PPTFake答辩PPT生成器
    PPTFake答辩PPT生成器,专为答辩准备设计,极致高效生成PPT与自述稿。智能解析内容,提供多样模板,数据可视化,贴心配套服务,灵活自主编辑,降低制作门槛,适用于各类答辩场景。
    36次使用
  • SEO标题Lovart AI:全球首个设计领域AI智能体,实现全链路设计自动化
    Lovart
    SEO摘要探索Lovart AI,这款专注于设计领域的AI智能体,通过多模态模型集成和智能任务拆解,实现全链路设计自动化。无论是品牌全案设计、广告与视频制作,还是文创内容创作,Lovart AI都能满足您的需求,提升设计效率,降低成本。
    48次使用
  • 美图AI抠图:行业领先的智能图像处理技术,3秒出图,精准无误
    美图AI抠图
    美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
    45次使用
  • SEO标题PetGPT:智能桌面宠物程序,结合AI对话的个性化陪伴工具
    PetGPT
    SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
    45次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码