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 (
    "time"

    "github.com/go-redis/redis"
    errors "github.com/pkg/errors"
)

var newRedisClient = redis.NewClient

// Options - My Redis Connection Options
type Options struct {
    *redis.Options
    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 (
    "testing"

    "github.com/go-redis/redis"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
)

type redisStatusCmdMock struct {
    mock.Mock
}

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

type redisClientMock struct {
    mock.Mock
}

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("127.0.0.1:1001", options.Addr)
        assert.Equal("password", options.Password)
        assert.Equal(1, options.DB)

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

        clientMock := new(redisClientMock)
        clientMock.On("Ping").Return(statusCmdMock)

        return clientMock
    }

    options := Options{}
    options.Addr = "127.0.0.1:1001"
    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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同