我正在编写一个处理将一些自定义指标存储到数据存储的 Go 模块。数据的性质使 Redis 非常理想,但使用接口(interface)以防万一需要更改是有意义的。我有以下代码:
type MetricsStore interface {
Put(metric string) (string, error)
Get(id string) (string, error)
}
然后我有一个结构,其中包含一个 Redis 客户端和一个
New()
创建结构实例并使用传递给函数的参数实例化 Redis 客户端的函数。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 接口(interface)上定义的函数。这里的问题是,自从
New()
函数创建 Redis 客户端并在 MetricsRedisCache
中返回它struct,在为 Put()
编写单元测试时,我无法轻松创建要使用的模拟客户端和 Get()
需要 MetricsRedisCache
的函数通过接收器。
最佳答案
创建一个新的构造函数,NewWithClient
或一些将客户端作为参数而不是创建它的方法。然后它返回一个 MetricsRedisCache
使用给定的客户端。您可以在测试中使用此构造函数来练习 MetricsRedisCache
的逻辑。使用模拟 Redis 客户端。
关于unit-testing - 当连接位于结构中时,我应该如何在 Go 中模拟 Redis 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61178543/