英文:
How to mock redis connection in Go
问题
你好!你可以使用Go语言的mock库来模拟Redis数据库调用。常用的Go语言mock库有testify/mock
和gomock
。你可以在这些库的文档中找到详细的使用方法和示例。希望对你有帮助!
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论