![](/img/trans.png)
[英]Deserialize cursor into array with mongo-go-driver and interface
[英]How to mock cursor with mongo-go-driver
I just learned go language, and then used https://github.com/mongodb/mongo-go-driver for make rest API with MongoDB and Golang and then I'm doing a unit test, but I'm stuck when mocking Cursor MongoDB,因為 Cursor 是一個結構,這是一個想法還是有人做出來的?
在我看來,mocking 這種對象的最佳方法是定義一個接口,因為在 go 接口是隱式實現的,您的代碼可能不需要那么多更改。 一旦你有了一個接口,你就可以使用一些第三方庫來自動生成模擬,比如模擬
關於如何創建接口的示例
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
只需更改接收 mongodb cursor 的任何 function 以使用自定義接口
我剛剛遇到了這個問題。 因為mongo.Cursor
有一個內部字段保存[]byte
- Current
,為了完全模擬你需要包裝mongo.Cursor
。 以下是我為此所做的類型:
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
}
不幸的是,這將是一個移動的目標。 隨着時間的推移,我將不得不向MongoCollection
接口添加新功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.