简体   繁体   English

如何在Go中模拟redis连接

[英]How to mock redis connection in Go

I am using https://github.com/go-redis/redis package to make Redis DB calls. 我正在使用https://github.com/go-redis/redis包来进行Redis数据库调用。 For unit testing I want to mock this calls, is there any mock library or way to do it? 对于单元测试我想模拟这个调用,是否有任何模拟库或方法来做?

Thank you all for the response. 谢谢大家的回复。 I found this package https://github.com/alicebob/miniredis very useful for redis mocking. 我发现这个包https://github.com/alicebob/minired对redis mocking非常有用。

It's even easier to mock using miniredis than is apparent at first glance. 使用miniredis进行模拟比乍一看更容易。 You don't need to mock every function like Get, Set, ZAdd etc. You can just start miniredis and inject its address to the actual client being used in code (eg go-redis ) this way: 您不需要模拟Get,Set,ZAdd等所有函数。您可以启动miniredis并将其地址注入到代码中使用的实际客户端(例如go-redis ):

mr := miniredis.Run()
redis.NewClient(&redis.Options{
            Addr: mr.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. 这也使您能够无缝地使用Pipelined()TxPipelined()等,即使miniredis没有明确地公开这些方法。

as @Motakjuq said, create an interface like this 正如@Motakjuq所说,创建一个这样的界面

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. 并在您的代码中使用实际的redis客户端( 如此 )并在测试中使用miniredis实现它。

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

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