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 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题