如何在一个方法中调用另一个方法
时间:2024-02-29
浏览:495
作者:佚名
本篇文章给大家分享《如何在一个方法中调用另一个方法》,覆盖了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)。 clientresponse 对 httpdoer 的具体实现一无所知,只知道它遵循接口!
i wrote a blog post 详细介绍了单元测试上下文中的依赖注入。
终于介绍完啦!小伙伴们,这篇关于《如何在一个方法中调用另一个方法》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
