当前位置:首页 > 文章列表 > Golang > Go问答 > 如何在一个方法中调用另一个方法

如何在一个方法中调用另一个方法

来源:stackoverflow 2024-02-29 16:27:24 0浏览 收藏

本篇文章给大家分享《如何在一个方法中调用另一个方法》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在编写一个网络应用程序,它将向第三方服务发送请求以进行一些计算,并将其发送回前端。

以下是我要编写的测试的相关部分。

客户端.go

func (c *clientresponse) getbankaccounts() (*bankaccounts, *requesterror) {
    req, _ := http.newrequest("get", app.buildurl("bank_accounts"), nil)
    params := req.url.query()
    params.add("view", "standard_bank_accounts")
    req.url.rawquery = params.encode()

    c.clientdo(req)
    if c.err.errors != nil {
        return nil, c.err
    }

    bankaccounts := new(bankaccounts)
    defer c.response.body.close()
    if err := json.newdecoder(c.response.body).decode(bankaccounts); err != nil {
        return nil, &requesterror{errors: &errors{error{message: "failed to decode bank account response body"}}}
    }

    return bankaccounts, nil
}

助手go

type clientresponse struct {
    response *http.response
    err      *requesterror
}

type clienti interface {
    clintdo(req *http.request) (*http.response, *requesterror)
}

func (c *clientresponse) clientdo(req *http.request) {
    //do some authentication with third-party service

    errresp := *new(requesterror)
    client := http.client{}
    resp, err := client.do(req)
    if err != nil {
        // here i'm repourposing the third-party service's error response mapping
        errresp.errors.error.message = "internal server error. failed create client.do"
    }
    c.response = resp
    c.err = &errresp
}

我只想测试 getbankaccounts() 方法,所以我想存根 clientdo,但我不知道如何做到这一点。这是我迄今为止的测试用例。

client_test.go

type stubclienti interface {
    clintdo(req *http.request) (*http.response, *requesterror)
}

type stubclientresponse struct {}

func (c *stubclientresponse) clientdo(req *http.request) (*http.response, *requesterror) {
    return nil, nil
}

func testgetbankaccounts(t *testing.t) {
    cr := new(clientresponse)
    accounts, err := cr.getbankaccounts()
    if err != nil {
        t.fatal(err.errors)
    }
    t.log(accounts)
}

clintdo仍然指向helper.go上的实际方法,我怎样才能让它在测试中使用on?

更新: 我也尝试了以下方法,但这也不起作用,它仍然将请求发送到实际的第三方服务。

client_test.go

func testgetbankaccounts(t *testing.t) {
    mux := http.newservemux()
    mux.handle("/", http.handlerfunc(func(w http.responsewriter, r *http.request) {
        w.writeheader(http.statusok)
        fmt.fprint(w, tojson(append(bankaccounts{}.bankaccounts, bankaccount{
            url:  "https://foo.bar/v2/bank_accounts/1234",
            name: "test bank",
        })))
    }))
    server := httptest.newserver(mux)
    cr := new(clientresponse)
    cr.client = server.client()
    accounts, err := cr.getbankaccounts()
    if err != nil {
        t.fatal(err.errors)
    }
    t.log(accounts)
}

助手go

type clientresponse struct {
    client   *http.client
    response *http.response
    err      *requesterror
}

type clienti interface {
    clintdo(req *http.request) (*http.response, *requesterror)
}

func (c *clientresponse) clientdo(req *http.request) {
    //do some authentication with third-party service

    errresp := *new(requesterror)
    client := c.client
    resp, err := client.do(req)
    if err != nil {
        // here i'm repourposing the third-party service's error response mapping
        errresp.errors.error.message = "internal server error. failed create client.do"
    }
    c.response = resp
    c.err = &errresp
}

更新2

我能够从 @dm03514 的答案中取得一些进展,但不幸的是,现在我在测试中得到了零指针异常,但在实际代码中却没有得到。

客户端.go

func (c *clientresponse) getbankaccounts() (*bankaccounts, *requesterror) {
    req, _ := http.newrequest("get", app.buildurl("bank_accounts"), nil)
    params := req.url.query()
    params.add("view", "standard_bank_accounts")
    req.url.rawquery = params.encode()

    //cr := new(clientresponse)
    c.httpdoer.clientdo(req)
    // panic occurs here
    if c.err.errors != nil {
        return nil, c.err
    }

    bankaccounts := new(bankaccounts)
    defer c.response.body.close()
    if err := json.newdecoder(c.response.body).decode(bankaccounts); err != nil {
        return nil, &requesterror{errors: &errors{error{message: "failed to decode bank account response body"}}}
    }

    return bankaccounts, nil
}

助手go

type clientresponse struct {
    response *http.response
    err      *requesterror
    httpdoer httpdoer
}

type httpdoer interface {
    //do(req *http.request) (*http.response, *requesterror)
    clientdo(req *http.request)
}

type clienti interface {
}

func (c *clientresponse) clientdo(req *http.request) {
  // this method hasn't changed
  ....
}

client_test.go

type stubdoer struct {
    *clientresponse
}

func (s *stubdoer) clientdo(req *http.request) {
    s.response = &http.response{
        statuscode: 200,
        body:       nil,
    }
    s.err = nil
}

func testgetbankaccounts(t *testing.t) {
    sd := new(stubdoer)
    cr := new(clientresponse)
    cr.httpdoer = httpdoer(sd)
    accounts, err := cr.getbankaccounts()
    if err != nil {
        t.fatal(err.errors)
    }
    t.log(accounts)
}
=== RUN   TestGetBankAccounts
--- FAIL: TestGetBankAccounts (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x12aae69]

解决方案


有两种常见方法可以实现此目的:

  • Dependency Injection 使用界面(您的示例)
  • 自定义 http.transport,它有一个可以在单元测试中覆盖的挂钩

看起来您已经接近接口方法,并且缺乏配置具体实现的显式方法。考虑一个类似于您的 clientdo 的界面:

type httpdoer interface {
  do func(req *http.request) (*http.response, *requesterror)
}

依赖注入让调用者配置依赖关系并将它们传递到实际调用这些依赖关系的资源中。在这种情况下,您的 clientresponse 结构将引用 httpdoer

type clientresponse struct {
    response *http.response
    err      *requesterror
    httpdoer httpdoer
}

这允许调用者配置 clientresponse 将调用的具体实现。在生产中,这将是实际的 http.client 但在测试中,它可以是实现 do 函数的任何内容。

type stubdoer struct {}

func (s *stubdoer) do(....)

单元测试可以配置stubdoer,然后调用getbankaccounts,然后进行断言:

sd := &StubDoer{...}
cr := ClientResponse{
   HTTPDoer: sd,
}
accounts, err := cr.GetBankAccounts()
// assertions

它被称为依赖注入的原因是调用者初始化资源(stubdoer),然后将该资源提供给目标(clientresponse)。 clientresponsehttpdoer 的具体实现一无所知,只知道它遵循接口!

i wrote a blog post 详细介绍了单元测试上下文中的依赖注入。

终于介绍完啦!小伙伴们,这篇关于《如何在一个方法中调用另一个方法》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
指南:学习如何在Golang中创建和使用动态库指南:学习如何在Golang中创建和使用动态库
上一篇
指南:学习如何在Golang中创建和使用动态库
PHP 类和对象实践指南:掌握优秀面向对象编程的技巧
下一篇
PHP 类和对象实践指南:掌握优秀面向对象编程的技巧
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ljg-skills -
    ljg-skills
    ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
    280次使用
  • MELO音乐 - AI 音乐生成平台,支持多模态创作能力
    MELO音乐
    MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
    297次使用
  • UniScribe - AI 免费在线音视频转文字平台
    UniScribe
    UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
    268次使用
  • 剧云 - 免费 AI 智能中文剧本创作平台
    剧云
    剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
    439次使用
  • 万象有声 - AI 一站式有声内容创作平台
    万象有声
    万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
    428次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码