2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
在我看來(lái),模擬此類對(duì)象的最佳方法是定義一個(gè)接口,因?yàn)?go 接口是隱式實(shí)現(xiàn)的,您的代碼可能不需要那么多更改。一旦你有了一個(gè)界面,你就可以使用一些第三方庫(kù)來(lái)自動(dòng)生成模擬,比如嘲笑
有關(guān)如何創(chuàng)建界面的示例
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
只需更改任何接收 mongodb 游標(biāo)的函數(shù)即可使用自定義接口

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
我剛剛遇到這個(gè)問(wèn)題。因?yàn)閙ongo.Cursor有一個(gè)內(nèi)部字段保存[]byte-- Current,為了完全模擬,您需要包裝mongo.Cursor. 以下是我為此創(chuàng)建的類型:
type MongoCollection interface {
Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (MongoCursor, error)
FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) MongoDecoder
Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (MongoCursor, error)
}
type MongoDecoder interface {
DecodeBytes() (bson.Raw, error)
Decode(val interface{}) error
Err() error
}
type MongoCursor interface {
Decode(val interface{}) error
Err() error
Next(ctx context.Context) bool
Close(ctx context.Context) error
ID() int64
Current() bson.Raw
}
type mongoCursor struct {
mongo.Cursor
}
func (m *mongoCursor) Current() bson.Raw {
return m.Cursor.Current
}
不幸的是,這將是一個(gè)移動(dòng)的目標(biāo)。MongoCollection隨著時(shí)間的推移,我將不得不向界面添加新功能。
- 2 回答
- 0 關(guān)注
- 167 瀏覽
添加回答
舉報(bào)