如何在Go中模拟Redis连接

huangapple go评论103阅读模式
英文:

How to mock redis connection in Go

问题

你好!你可以使用Go语言的mock库来模拟Redis数据库调用。常用的Go语言mock库有testify/mockgomock。你可以在这些库的文档中找到详细的使用方法和示例。希望对你有帮助!

英文:

I am using https://github.com/go-redis/redis package to make Redis DB calls.

For unit testing I want to mock these calls, is there any mock library or way to do it?

答案1

得分: 20

使用miniredis进行模拟测试比看起来更容易。你不需要模拟每个函数,比如Get、Set、ZAdd等等。你可以启动miniredis并将其地址注入到实际在代码中使用的客户端中(比如go-redis):

server := miniredis.Run()
redis.NewClient(&redis.Options{
	Addr: server.Addr(),
})

不需要进一步的模拟测试。这样还可以无缝地使用Pipelined()TxPipelined()等方法,即使miniredis并没有显式地暴露这些方法。

英文:

It's even easier to mock using miniredis than is apparent. You don't need to mock every function like Get, Set, ZAdd, etc. You can start the miniredis and inject its address to the actual client being used in code (e.g. go-redis) this way:

server := miniredis.Run()
redis.NewClient(&redis.Options{
	Addr: server.Addr(),
})

No further mocking would be required. This also enables you to seamlessly use Pipelined(), TxPipelined() etc. even though miniredis doesn't explicitly expose these methods.

答案2

得分: 8

谢谢大家的回复。我发现这个包https://github.com/alicebob/miniredis对于模拟Redis非常有用。

英文:

Thank you all for the response. I found this package https://github.com/alicebob/miniredis very useful for redis mocking.

答案3

得分: 0

根据@Motakjuq所说,创建一个如下所示的接口:

type DB interface {
   GetData(key string) (value string, error)
   SetData(key string, value string) error
}

然后在你的代码中使用实际的Redis客户端(例如这个)来实现它,并在测试中使用miniredis

英文:

as @Motakjuq said, create an interface like this

type DB interface {
   GetData(key string) (value string, error)
   SetData(key string, value string) error
}

and implement it with actual redis client (like this) in your code and miniredis in tests.

huangapple
  • 本文由 发表于 2017年6月24日 02:34:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/44727938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定