如何在Golang中的类型内模拟类型? [英] How do you mock a type within a type in Golang?

查看:43
本文介绍了如何在Golang中的类型内模拟类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'gopkg.in/redis.v3'软件包包含一些代码

The package 'gopkg.in/redis.v3' contains some code

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.

The problem is that sometimes the Redis cluster gets hammered, has a moment, and the interface returned as a result is nil.

这相当容易处理,但是我希望对它进行测试,以确保它能够被实际处理并且不会发生类型断言恐慌.

This is reasonably easy to handle but I wish to put a test in place that will ensure that it is actually handled and no type assertion panic occurs.

传统上,我会将模拟Redis客户端插入到myFunc中,最终可以返回nil.

Traditionally I would insert a mock Redis client into myFunc that can ultimately return 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.

The problem I am facing is the compiler doesn't recognise that redis.Client satisfies the interface redisClient because it doesn't recognise that the redis.Cmd returned from Eval satisfies 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客户端不匹配.如果您将界面更改为:

The problem is that your interface does not match the redis client. If you change the interface to:

type redisClient interface {
    Eval(string, []string, []string) *redis.Cmd
}

它将编译.话虽如此,看起来您确实想要rediscmd,所以您将需要对redis客户端进行包装:

it will compile. That being said, it looks like you really want rediscmd, so you will need to make a wrapper around the redis client:

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中的类型内模拟类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆