亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Golang 中測試接受不返回值的回調函數的方法

在 Golang 中測試接受不返回值的回調函數的方法

Go
胡子哥哥 2023-03-21 15:22:38
我正在嘗試測試以下功能:// 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 functiontype MySpy struct {    *spies.Spy}func (my *MySpy) Callback(res CallResultSt, data interface{}) {    my.Called(res, data)    fmt.Println("Hello world")    return}//in the test functionspy := new(MySpy)//...some table-driven test logic the generator came up with, containing my dataspy.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我該如何解決這個問題,并測試這個方法?
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

我會放棄間諜的東西。此任務非常簡單,您不需要外部依賴項來處理它。您可以改為制作自己的“間諜”,它有一個通道,它在調用函數時將 args 傳遞到其中。在您的測試中,您然后嘗試從頻道接收。這將強制測試等待回調函數被調用。您還可以考慮添加一個超時時間,這樣測試就可以失敗,而不是在函數從未被調用時永遠阻塞。


// 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

}


查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號