Mocking Redis In Unit Tests In Go

I created the package It useful for unit testing applications that interact with Redis. It uses the stretchr/testify mocking system.

Unlike using a real or fake Redis (more below), redismock provides normal and nice mocks for more flexibility in control behavior. One example might be to test the case where Redis takes too long to respond to a command, or returns an expected error without needing to setup beforehand.


This is most useful when you want to strictly test all Redis interactions.


This is most useful when you want a real Redis instance, but you need to stub off certain commands or behaviors.


It provides a huge interface for all of the Redis commands called Cmdable. You should use the Cmdable interface throughout your code, instead of the struct type. creates a fake Redis server that can be used by go-redis/redis which makes it fantastic for running unit tests since you do not need to run a separate Redis server. It also only retains state with the instance, so each test gets an empty Redis database each time.


import (
// newTestRedis returns a redis.Cmdable.
func newTestRedis() *redismock.ClientMock {
mr, err := miniredis.Run()
if err != nil {
client := redis.NewClient(&redis.Options{
Addr: mr.Addr(),
return redismock.NewNiceMock(client)
// This would be your production code.
func RedisIsAvailable(client redis.Cmdable) bool {
return client.Ping().Err() == nil
// Test Redis is down.
func TestRedisCannotBePinged(t *testing.T) {
r := newTestRedis()
Return(redis.NewStatusResult("", errors.New("server not available")))
assert.False(t, RedisIsAvailable(r))

Originally published at on August 21, 2018.

Written by

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store