我正在尝试为一个使用golang mongo驱动程序的新项目编写测试。遗憾的是,他们没有使用接口,所以我基本上是在尝试自己写下我正在使用的几个方法,但Go可能遗漏了一些东西。
假设我有以下struct,它是存储库部分的根:
type MongoChecksRunner struct {
Client ClientHelper
}ClientHelper是原*mongo.Client实现的如下接口:
type ClientHelper interface {
Database(name string, opts ...*options.DatabaseOptions) DatabaseHelper
Connect(ctx context.Context) error
}每一层都是接口的,所以对于原始的*mongo.Database结构,我们得到:
type DatabaseHelper interface {
RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) SingleResultHelper
}最后,对于原始的*mongo.SingleResult结构,我们有:
type SingleResultHelper interface {
Decode(v interface{}) error
Err() error
}但是,当我尝试实例化一个新的MongoChecksRunner时,它不能编译:
func NewMongoChecksRunner(host string, port int) (*MongoChecksRunner, error) {
client, err := mdriver.NewClient(
options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", host, port)),
options.Client().SetDirect(true),
)
if err != nil {
return nil, err
}
return &MongoChecksRunner{
Client: client,
}, nil
}我得到以下错误:cannot use client (variable of type *mongo.Client) as ClientHelper value in struct literal: wrong type for method Database。
Golang是否有任何限制,使您无法对接口进行多层嵌套?
请在下面找到原始mongo包结构的方法签名:
func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
func (c *Client) Connect(ctx context.Context) error
func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
func (sr *SingleResult) Decode(v interface{}) error
func (sr *SingleResult) Err() error预先感谢您的任何帮助
发布于 2021-08-14 09:35:02
用https://pkg.go.dev/github.com/256dpi/lungo模拟Mongo驱动程序,具有通用接口
https://stackoverflow.com/questions/58931684
复制相似问题