Mocking Redis In Unit Tests In Go

I created the package github.com/elliotchance/redismock. 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.

NewMock()

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

NewNiceMock(client)

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

Compatibility

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.

github.com/alicebob/miniredis 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.

Example

import (
"testing"
"github.com/go-redis/redis"
"github.com/alicebob/miniredis"
"github.com/elliotchance/redismock"
"errors"
"github.com/stretchr/testify/assert"
)
// newTestRedis returns a redis.Cmdable.
func newTestRedis() *redismock.ClientMock {
mr, err := miniredis.Run()
if err != nil {
panic(err)
}
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()
r.On("Ping").
Return(redis.NewStatusResult("", errors.New("server not available")))
assert.False(t, RedisIsAvailable(r))
}

Originally published at http://elliot.land 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. 🤓 elliotchance@gmail.com

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