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 qteasy 运行前进中
  • ¥15 我想通过python处理sybase IQ库的一些数据,但是不知道sybase IQ库怎么连接,之前连接都是用linux上的 dbisql
  • ¥15 安装llama-cpp-python==0.1.83失败
  • ¥20 管道轴向耦合水击问题
  • ¥60 补全networkx TODO部分。
  • ¥15 有内推吗,云计算linux运维方向
  • ¥30 sort cuteSV.vcf by bcftools用IGV可视化出现报错
  • ¥100 SOS!对STK中导出的天体图像进行质心提取有没有人做过啊
  • ¥15 python 欧式距离
  • ¥15 遗传算法解决有工序顺序约束的大规模FJSP问题