'How to mock redis connection in Go
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?
Solution 1:[1]
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.
Solution 2:[2]
Thank you all for the response. I found this package https://github.com/alicebob/miniredis very useful for redis mocking.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amin Shojaei |
Solution 2 | rovy |
Solution 3 | Asalle |