如何在golang中模拟redis

问题描述 投票:0回答:1

我一直在golang中使用redismock(github.com/go-redis/redismock/v8), 我有生成 otp 的情况,并且 otp 将存储在 redis 中 像这样“call to cmd '[set 0888888888 4980 ex 300]”,有没有像testify有mock这样的解决方案。任何东西,但是在redismock中,我需要在redismock中自动参数模拟以匹配实际值,谢谢

这是我的单元测试的行代码

suite.mockRedis.ExpectSet(repotest.DummyUser.PhoneNumber, "otp", ttl).SetVal("otp")

这是 otp 生成并存储到 redis 的地方

otp, err := a.generateAndSendOTPTelegram(c, user.TelegramId)

err = a.Client.StoreOTPInRedis(*user, otp)

我想匹配实际的otp,因为它是生成的而不是恒定的,我需要一些类似mock的东西。redismock中的testify有什么东西,有什么解决方案吗?

go redis
1个回答
0
投票

在我看来,你可以利用

miniredis
https://github.com/alicebob/miniredis

可以通过

miniredis
制作模拟redis,并将数据写入其中。 您可以使用您的客户端代码来测试它。

示例

package __06_2

import (
    "context"
    "fmt"
    "testing"

    "github.com/alicebob/miniredis/v2"
    "github.com/redis/go-redis/v9"
)

func TestSomething(t *testing.T) {

    // 1. Set the mock redis and data on it.
    s := miniredis.RunT(t)

    _ = s.Set("otp", "privatePassword")

    // 2. Set the client for accessing the mock redis
    rdb := redis.NewClient(&redis.Options{
        Addr:     s.Addr(),
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    // 3. Accessing the data from the mock redis
    var ctx = context.Background()
    val, err := rdb.Get(ctx, "otp").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)
}

输出

=== RUN   TestSomething
key privatePassword
--- PASS: TestSomething (0.00s)
PASS

© www.soinside.com 2019 - 2024. All rights reserved.