模拟mgo链接功能 [英] Mocking mgo chaining functions
问题描述
在测试我的一些代码库时,我发现用接口模拟"gopkg.in/mgo.v2"中的对象很有用.我遇到了一个问题,其中mgo.Query无法实现我的接口Query.
While testing some of my codebase I found it useful to mock out objects from "gopkg.in/mgo.v2" with interfaces. I'm running into a problem where mgo.Query does not implement my interface Query.
import mgo "gopkg.in/mgo.v2"
type Collection interface {
FindId(interface{}) Query
Find(interface{}) Query
UpdateId(interface{}, interface{}) error
Update(interface{}, interface{}) error
UpsertId(interface{}, interface{}) (interface{}, error)
Insert(...interface{}) error
RemoveId(interface{}) error
}
type Query interface {
One(interface{}) error
All(interface{}) error
Select(interface{}) Query
}
var _ Query = (*mgo.Query)(nil)
查询强制转换引发错误:
The Query cast kicks up the error:
cannot use (*mgo.Query)(nil) (type *mgo.Query) as type Query in assignment:
*mgo.Query does not implement Query (wrong type for Select method)
have Select(interface {}) *mgo.Query
want Select(interface {}) Query
这是链函数无法在接口中定义的问题吗?我不确定如何制作与mgo实现匹配的Select标头.
Is this a problem with chain functions not being able to be defined in an interface? I'm not sure how to make a Select header that will match the mgo implementation.
推荐答案
函数签名不同,这就是为什么您遇到编译错误的原因.接口版本的Select
返回您的 Query
类型,而mgo的Select
返回*mgo.Query
,这是另一种类型.即使该类型确实实现了您的接口,功能签名仍然不同.您将需要在其中添加另一层以便包裹mgo软件包.
The function signatures are different, which is why you're running into a compilation error. Your interface version of Select
returns your Query
type, while mgo's Select
returns *mgo.Query
, which is a different type. Even if that type does implement your interface, the function signatures are still different. You will need to add another layer to this where you are able to wrap the mgo package.
type MgoQuery struct {
*mgo.Query
}
func (q *MgoQuery) Select(selector interface{}) Query {
return q.Query.Select(selector)
}
...
这篇关于模拟mgo链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!