【发布时间】:2019-09-17 04:59:59
【问题描述】:
我需要定义这些接口来模拟官方的mongo驱动
type MgCollection interface {
FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult
// Other methods
}
type MgDatabase interface {
Collection(name string, opts ...*options.CollectionOptions) MgCollection
// Other methods
}
在 mongo 驱动程序包中有两个结构 mongo.Collection 和 mongo.Database 带有这些方法
func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *SingleResult {
// Method code
}
func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection {
// Method code
}
结构体*mongo.Collection正确实现MgCollection,所以这段代码编译没有错误
var col mgdriver.MgCollection
col = &mongo.Collection{}
col.FindOne(ctx, nil, nil)
但是结构*mongo.Database没有实现MgDatabase,所以我写的时候是这样的:
var db mgdriver.MgDatabase
db = &mongo.Database{}
db.Collection("Test", nil)
编译器显示此错误:
不能使用 &mongo.Database literal (type *mongo.Database) 作为类型 分配中的 mgdriver.MgDatabase:*mongo.Database 未实现 mgdriver.MgDatabase(Collection 方法的类型错误)有 集合(字符串,...*options.CollectionOptions)*mongo.Collection 想要 Collection(string, ...*options.CollectionOptions) mgdriver.MgCollection
mongo.Collection 和 mongo.Database 都在官方包中,我无法更改该包中的任何代码。那么如何更改我的接口以正确模拟官方 mongo 驱动程序?
【问题讨论】:
标签: mongodb unit-testing go mocking