当前位置:首页 > 文章列表 > 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推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    3164次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    3376次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    3405次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    4509次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    3785次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码