登录
首页 >  Golang >  Go问答

在 Golang 中测试接受无返回值回调函数的方式

来源:stackoverflow

时间:2024-03-13 14:24:28 453浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《在 Golang 中测试接受无返回值回调函数的方式》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在尝试测试以下功能:

// sendrequestasync sends request asynchronously, accepts callback
//  func, which it invokes
//
// parameters:
// - `context` : some context
// - `token` : some token
// - `apiurl` : the url to hit
// - `calltype` : the type of request to make. this should be one of
//  the http verbs (`"get"`, `"post"`, `"put"`, `"delete"`, ...)
// - `callback` : the func to invoke upon completion
// - `callbackcustomdata`: the data to invoke `callback` with
//
// since this is an async request, it doesn't return anything.
func (a *apicorest) sendrequestasync(context interface{}, token string, apiurl string, calltype apitype, header map[string]string, jsonbody []byte,
    callback oncompletion, callbackcustomdata interface{}) {
    go func(data interface{}) {
        callback(a.sendrequest(context, token, apiurl, calltype, header, jsonbody), data)
    }(callbackcustomdata)
}

其中 oncompletion 定义为:

type oncompletion func(result callresultst, data interface{})

我的想法立即想到创建一个间谍回调。为此,我分叉了这个框架,提出了以下内容:

// outside the test function
type myspy struct {
    *spies.spy
}

func (my *myspy) callback(res callresultst, data interface{}) {
    my.called(res, data)
    fmt.println("hello world")
    return
}

//in the test function
spy := new(myspy)

//...some table-driven test logic the generator came up with, containing my data

spy.matchmethod("callback", spies.anyargs)
assert.notempty(t, spies.callsto("callback"))

它向我打招呼

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference

我该如何解决这个问题并测试这个方法?


解决方案


我会放弃间谍的东西。此任务非常简单,您不需要外部依赖项来处理它。您可以创建自己的“间谍”,它有一个在调用函数时将参数传递到其中的通道。在您的测试中,您然后尝试从该通道接收。这将迫使测试等待回调函数被调用。您还可以考虑添加一个超时时间,以便测试可以失败,而不是在函数从未被调用的情况下永远阻塞。

// outside the test function
type myspy struct {
    args chan myspyargs
}

type myspyargs struct {
    res  callresultst
    data interface{}            
}

func (my *myspy) callback(res callresultst, data interface{}) {
    my.args <- myspyargs{res: res, data: data}
}

//in the test function
spychan := make(chan myspyargs)
spy := &myspy{spychan}

//...some table-driven test logic the generator came up with, containing my data

args := <-spychan
// can now assert arguments were as you expected, etc.

一个粗略的工作示例:https://play.golang.org/p/zUYpjXdkz-4

如果你想使用超时:

...
select {
case args := <-spyChan:
    // assertions on args
case <-time.After(5 * time.Second):
    // prevent blocking for over 5 seconds and probably fail the test
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>