duanpao6163 2019-09-19 17:50
浏览 25


I'm fairly new to Go and I'm having some issues with writing tests, specifically mocking the response of a package function.

I'm writing an wrapper lib for github.com/go-redis/redis. At the moment it only really has better errors for failures, but it will be expanded with statsd tracking further down the line, but I digress...

I have the following go package that I have created

package myredis

import (

    errors "github.com/pkg/errors"

var newRedisClient = redis.NewClient

// Options - My Redis Connection Options
type Options struct {
    DefaultLifetime time.Duration

// MyRedis - My Redis Type
type MyRedis struct {
    options Options
    client  *redis.Client

// Connect - Connects to the Redis Server. Returns an error on failure
func (r *MyRedis) Connect() error {

    r.client = newRedisClient(&redis.Options{
        Addr:     r.options.Addr,
        Password: r.options.Password,
        DB:       r.options.DB,

    _, err := r.client.Ping().Result()
    if err != nil {
        return errors.Wrap(err, "myredis")

    return nil

My problem is that I want redis.NewClient to return a mock. This is the test code that I wrote, but it's not working:

package myredis

import (


type redisStatusCmdMock struct {

func (m *redisStatusCmdMock) Result() (string, error) {
    args := m.Called()
    return args.Get(0).(string), args.Error(1)

type redisClientMock struct {

func (m *redisClientMock) Ping() redis.StatusCmd {
    args := m.Called()
    return args.Get(0).(redis.StatusCmd)

func TestConnect(t *testing.T) {
    assert := assert.New(t)

    old := newRedisClient
    defer func() { newRedisClient = old }()

    newRedisClient = func(options *redis.Options) *redis.Client {
        assert.Equal("", options.Addr)
        assert.Equal("password", options.Password)
        assert.Equal(1, options.DB)

        statusCmdMock := new(redisStatusCmdMock)
        statusCmdMock.On("Result").Return("success", nil)

        clientMock := new(redisClientMock)

        return clientMock

    options := Options{}
    options.Addr = ""
    options.Password = "password"
    options.DB = 1

    r := MyRedis{options: options}

    result, err := r.Connect()

    assert.Equal("success", result)
    assert.Equal(nil, err)

I get the following error: cannot use clientMock (type *redisClientMock) as type *redis.Client in return argument. I think I read that I need to mock all the functions of redis.Client in order to be able to use it as a mock in this case, but is that really the case? That seems like it's overkill and I should be able to do this in some way. How do I go about getting this test to work, or do I need to restructure my code so that it's easier to write the test?

  • 写回答

1条回答 默认 最新

  • duanbi2760 2019-09-20 06:29

    redis.Client is a struct type and in Go struct types are simply not mockable. However interfaces in Go are mockable, so what you can do is to define your own "newredisclient" func that instead of returning a struct returns an interface. And since interfaces in Go are satisfied implicitly you can define your interface such that it will be implemented by redis.Client out of the box.

    type RedisClient interface {
        Ping() redis.StatusCmd
        // include any other methods that you need to use from redis
    func NewRedisCliennt(options *redis.Options) RedisClient {
        return redis.NewClient(options)
    var newRedisClient = NewRedisClient

    If you also want to mock the return value from Ping(), you need to do a bit more work.

    // First define an interface that will replace the concrete redis.StatusCmd.
    type RedisStatusCmd interface {
        Result() (string, error)
        // include any other methods that you need to use from redis.StatusCmd
    // Have the client interface return the new RedisStatusCmd interface
    // instead of the concrete redis.StatusCmd type.
    type RedisClient interface {
        Ping() RedisStatusCmd
        // include any other methods that you need to use from redis.Client

    Now *redis.Client does not satisfy the RedisClient interface anymore because the return type of Ping() is different. Note that it doesn't matter that the result type of redis.Client.Ping() satisfies the interface type returned by RedisClient.Ping(), what matters is that the method signatures are different and therefore their types are different.

    To fix this you can define a thin wrapper that uses *redis.Client directly and also satisfies the new RedisClient interface.

    type redisclient struct {
        rc *redis.Client
    func (c *redisclient) Ping() RedisStatusCmd {
        return c.rc.Ping()
    func NewRedisCliennt(options *redis.Options) RedisClient {
        // here wrap the *redis.Client into *redisclient
        return &redisclient{redis.NewClient(options)}
    var newRedisClient = NewRedisClient
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 计算300m以内的LD衰减
  • ¥15 Lxml库中Xpath查找指定节点
  • ¥15 数据爬取,python
  • ¥15 怎么看 cst中一个面的功率分布图,请说明详细步骤。类似下图
  • ¥15 为什么我的pycharm无法用pyqt6的QtWebEngine
  • ¥15 FOR循环语句显示查询超过300S错误怎么办
  • ¥15 数电设计题 没有设计思路 不知道用什么芯片进行设计 求提供设计思路
  • ¥60 设计一种优化算法结合案例给出智能仓储四向穿梭车的调度计划
  • ¥15 Errno2:No such file or directory,在当前文件确实没有该图片,怎么解决?
  • ¥15 博世摄像头数据存储的问题(iscsi)