繁体   English   中英

当连接位于结构中时,我应该如何在 Go 中模拟 Redis 连接?

[英]How should I mock a Redis connection in Go when the connection is in a struct?

我正在编写一个 Go 模块,用于将一些自定义指标存储到数据存储中。 数据的性质使 Redis 成为理想选择,但使用接口以防万一需要更改是有意义的。 我有以下代码:

type MetricsStore interface {
    Put(metric string) (string, error)
    Get(id string) (string, error)
}

I then have a struct that contains a Redis client, and a New() function which creates an instance of the struct and instantiates the Redis client using the parameters passed into the function.

type MetricsRedisCache struct {
    c *redis.Client
}

func New(address string, password string, db int) (MetricsRedisCache) {
    options := &redis.Options{
        Addr:               address,
        Password:           password,
        DB:                 db,
    }

    return RedisUrlStore{client: redis.NewClient(options)}
}

MetricsRedisCache 然后实现 MetricsStore 接口上定义的函数。 这里的问题是,由于New() function 创建了 Redis 客户端并将其返回到MetricsRedisCache结构中,因此在为Put()Get()函数编写单元测试时,我无法轻松创建一个模拟客户端来使用通过接收器获取MetricsRedisCache

创建一个新的构造函数, NewWithClient或其他将客户端作为参数而不是创建它的构造函数。 然后它使用给定的客户端返回一个MetricsRedisCache 您可以在测试中使用此构造函数来使用模拟 Redis 客户端来练习MetricsRedisCache的逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM