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

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

Golang Mocking - 類型沖突問題

Golang Mocking - 類型沖突問題

Go
MMTTMM 2021-11-15 20:56:26
我正在模擬一個 DataStore 和它的獲取/設置功能。我遇到的問題是:不能在 EventHandler 的參數中使用 s (type *MockStore) 作為類型 *datastore.Storage這是由于我的 EventHandler 函數需要將 *datastore.Storage 作為參數類型傳遞。我想使用我創建的 MockStore 而不是真正的數據存儲來測試(http 測試)EvenHandler()。我正在使用 golang testify 模擬包。一些代碼示例type MockStore struct{  mock.Mock}func (s *MockStore) Get() ... func EventHandler(w http.ResponseWriter, r *http.Request, bucket *datastore.Storage){  //Does HTTP stuff and stores things in a data store  // Need to mock out the data store get/sets}// Later in my Testsms := MockStoreEventHandler(w,r,ms)
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

一些東西:

  • 創建一個將由datastore.Storage您的模擬商店實現的接口。

  • 使用上述接口作為參數類型 in EventHandler (not a pointer to the interface)

  • 將指針傳遞給您的MockStoreto EventHandler,因為該Get方法是為指向結構的指針定義的。

您更新后的代碼應如下所示:

type Store interface {

   Get() (interface{}, bool) // change as needed

   Set(interface{}) bool

}


type MockStore struct {

   mock.Mock

}


func (s *MockStore) Get() ... 


func EventHandler(w http.ResponseWriter, r *http.Request,bucket datastore.Storage){

   //Does HTTP stuff and stores things in a data store

   // Need to mock out the data store get/sets

}



// Later in my Tests

ms := &MockStore{}

EventHandler(w,r,ms)


查看完整回答
反對 回復 2021-11-15
  • 1 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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