登录
首页 >  Golang >  Go问答

MongoDB官方驱动程序的模拟

来源:stackoverflow

时间:2024-03-13 15:09:27 409浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《MongoDB官方驱动程序的模拟》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我需要定义这些接口来模拟官方 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.collectionmongo.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 文字(类型 *mongo.database)作为类型 分配中的 mgdriver.mgdatabase:*mongo.database 未实现 mgdriver.mgdatabase(集合方法的类型错误)有 集合(字符串,...*options.collectionoptions)*mongo.collection 想要 collection(字符串, ...*options.collectionoptions) mgdriver.mgcollection

mongo.collectionmongo.database 都在官方包中,我无法更改该包中的任何代码。那么如何正确更改接口以模拟官方 mongo 驱动程序呢?


解决方案


通常情况下,你不会。你应该做的是定义一个数据访问接口,

type crud interface {
  create(yourmodel) error
  read(page, size, skip) []yourmodel
  update(yourmodel) error
  delete(yourmodel) error
}

并实施它。

然后您可以模拟该接口,例如使用 testify/mock

type mockedcrud struct {
  mock.mock
}

func(m *mockedcrud)create(y yourmodel) error{
  returned m.called(y).error(0)
}
// and so on and so forth

由于 mockedcrud 满足 crud 接口,因此您可以像使用 mongocrud 实现一样使用它,没有任何麻烦:

func TestYourApplicationLogicCallingCreate( t *testing.T){
    model := YourModel{Type: ”Baz”})

    mocked := new(MockedCRUD)
    mocked.On(”Create”,model).Return(ErrInvalidType)

    app := YourApplication{CRUD:mocked}

    err := app.yourApplicationLogicCallingCreate(model)

    assert.Error(t,err)
    assert.Equal(t,ErrInvalidType,err)

}

剩下的问题是如何测试 crud 接口的实现。我曾经使用mgo驱动程序,最初由gustavo niemeyer开发,并由globalsign接管。这带来了一个名为 dbtest 的漂亮小包。它实际上是 mongodb 实例的一个非常薄的包装器,可以按需启动和停止一个实例,并且能够在测试之间重置数据。要么直接导入 dbtest,要么引用 go 谚语

(不过,请记住注明出处,并保留版权说明。)

因此,使用上述方法,您可以非常快速地针对模拟进行单元测试,并为您的测试提供稳定且可预测的答案,并且仅在绝对必要时才针对 mongodb 进行相对昂贵且缓慢的测试。

额外的好处:更换实际的持久性技术相对容易。

终于介绍完啦!小伙伴们,这篇关于《MongoDB官方驱动程序的模拟》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>