如何在Golang中的类型内模拟类型?
软件包“ gopkg.in/redis.v3”包含一些代码
type Client struct {}
func (*client) Eval (string, []string, []string) *Cmd {
}
type Cmd struct {
}
func (*Cmd) Result () (interface{}, error) {
}
哪个以以下方式成功工作
func myFunc (cli *redis.Client) { result, err := cli.Eval('my script').Result()
}
问题在于,有时Redis集群会受到重击,有片刻,结果返回的接口为nil。
这是相当容易处理的,但是我希望进行测试以确保它被实际处理并且不会发生类型断言恐慌。
传统上,我会将模拟Redis客户端插入myFunc中,该客户端最终会返回nil。
type redisClient interface { Eval(string, []string, []string) redisCmd
}
type redisCmd interface {
Result() (interface{}, error)
}
func myFunc (cli redisClient) {
result, err := cli.Eval('my script').Result()
}
我面临的问题是编译器无法识别redis.Client满足接口redisClient,因为它无法识别从Eval返回的redis.Cmd满足redisCmd。
> cannot use client (type *redis.Client) as type redisClient in argument to myFunc:> *redis.Client does not implement redisClient (wrong type for Eval method)
> have Eval(sting, []string, []string) *redis.Cmd
> want Eval(sting, []string, []string) redisCmd
回答:
问题是您的界面与redis客户端不匹配。如果将接口更改为:
type redisClient interface { Eval(string, []string, []string) *redis.Cmd
}
它将编译。话虽如此,看起来您确实想要rediscmd
,所以您将需要对redis客户端进行包装:
type wrapper struct{ c *redis.Client
}
func (w wrapper) Eval(x sting, y []string, z []string) redisCmd {
return w.c.Eval(x,y,z) // This assumes that *redis.Cmd implements rediscmd
}
以上是 如何在Golang中的类型内模拟类型? 的全部内容, 来源链接: utcz.com/qa/400030.html