Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock redis connection in Go

Tags:

redis

mocking

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?

like image 732
rovy Avatar asked Jun 23 '17 18:06

rovy


People also ask

What is redis mock?

The goal of the redis-mock project is to create a feature-complete mock of node_redis, which may be used interchangeably when writing unit tests for code that depends on redis . All operations are performed in-memory, so no Redis installation is required.

Is redis written in Go?

GitHub - redis-go/redis: Redis server written in Go / Golang (prototype)

What is redis in Golang?

Redis is an in-memory data store used as a database, cache, or message broker. Go-redis/redis is a type-safe, Redis client library for Go with support for features like Pub/Sub, sentinel, and pipelining.


2 Answers

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

like image 97
rovy Avatar answered Sep 17 '22 20:09

rovy


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.

like image 42
Chayan Ghosh Avatar answered Sep 17 '22 20:09

Chayan Ghosh