当前位置:首页 > 文章列表 > 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基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 茅茅虫AIGC检测:精准识别AI生成内容,保障学术诚信
    茅茅虫AIGC检测
    茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
    25次使用
  • 赛林匹克平台:科技赛事聚合,赋能AI、算力、量子计算创新
    赛林匹克平台(Challympics)
    探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
    51次使用
  • SEO  笔格AIPPT:AI智能PPT制作,免费生成,高效演示
    笔格AIPPT
    SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
    58次使用
  • 稿定PPT:在线AI演示设计,高效PPT制作工具
    稿定PPT
    告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
    54次使用
  • Suno苏诺中文版:AI音乐创作平台,人人都是音乐家
    Suno苏诺中文版
    探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
    60次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码