如何基于 Cache 接口编写单元测试并替换为 memory 适配器?

解读

在国内一线/二线互联网公司的 Go 后端面试中,Beego 的 cache 模块常被用来考察候选人对“接口抽象 + 依赖注入 + 单测隔离”的掌握程度。
面试官真正想确认的是:

  1. 你是否理解 Beego 的 cache.Cache 接口,而非只会在配置文件里写 adapter=memory。
  2. 你是否能把“外部依赖”变成“可注入的依赖”,从而让单测在毫秒级、无端口、无文件、无网络的环境下跑完。
  3. 你是否会利用 memory 适配器“线程安全 + 自动过期”的特性,覆盖正常路径、异常路径、并发路径、过期路径四种场景。
  4. 你是否能写出“可维护”的单测:表驱动、子测试、并行、无全局状态、无 init() 魔术。

如果候选人只能说出“把 beego.AppConfig 里的 adapter 改成 memory”,只能给 40 分;能把接口注入、并发安全、过期回调、benchmark 都讲清楚,才能拿到 90+。

知识点

  1. Beego Cache 抽象层

    • 核心接口:cache.Cache(Get/Put/Delete/IsExist/Incr/Decr/StartAndGC)。
    • 所有适配器(memory、redis、file、memcache)均实现该接口,因此业务代码面向接口编程即可。
  2. 依赖注入姿势

    • 构造器注入:业务结构体里直接持有 cache.Cache 字段,由 main.go 注入真实适配器,单测注入 memory 适配器。
    • 配置隔离:单测目录下单独 app.conf,或完全不用配置文件,用代码显式 NewCache("memory", …)。
  3. memory 适配器特点

    • 基于 sync.RWMutex + map[string]*item,支持 expire 秒级过期。
    • 启动成本为零,不需要端口、网络、文件句柄,单测并发跑 1 万用例也能毫秒级结束。
    • 过期回调 ExpiredFunc 可注入,用于验证“缓存击穿/雪崩”逻辑。
  4. 单测编写规范(国内大厂 checklist)

    • 必须子测试:t.Run("caseName", func(t *testing.T){}),CI 失败时快速定位。
    • 必须并行:t.Parallel(),防止顺序跑拖慢 CI。
    • 必须表驱动:覆盖“key 为空/超长/二进制”、“value 为 nil/大对象”、“并发安全”、“过期精准度”四类。
    • 必须清零:每个用例结束后 cache.Delete() 或重新 NewCache,禁止全局 map 污染下一个用例。
  5. 性能验证

    • 附带 BenchmarkCacheGet/Set 证明 memory 适配器在 10 并发下 QPS 不低于 50 万,给面试官一个“量化”印象。

答案

下面给出可直接跑进面试官电脑的一段“生产级”示例,包含:

  • 业务代码:面向接口的 TokenService;
  • 单测文件:完全基于 memory 适配器,覆盖正常、并发、过期、异常四种场景;
  • 注入方式:构造器注入,零配置文件,零全局变量。
// token.go  业务代码
package user

import (
    "context"
    "time"

    "github.com/beego/beego/v2/client/cache"
)

type TokenService struct {
    store cache.Cache
    ttl   time.Duration
}

// NewTokenService 由 main 注入真实的 redis 实例,单测注入 memory 实例
func NewTokenService(c cache.Cache, ttl time.Duration) *TokenService {
    return &TokenService{store: c, ttl: ttl}
}

func (s *TokenService) SaveToken(ctx context.Context, uid string, token string) error {
    return s.store.Put(uid, token, s.ttl)
}

func (s *TokenService) VerifyToken(ctx context.Context, uid string, wantToken string) bool {
    got, err := s.store.Get(uid)
    if err != nil || got == nil {
        return false
    }
    return got.(string) == wantToken
}
// token_test.go  单测文件
package user

import (
    "context"
    "sync"
    "testing"
    "time"

    "github.com/beego/beego/v2/client/cache"
    "github.com/beego/beego/v2/client/cache/memory"
    "github.com/stretchr/testify/assert"
)

// 构造 memory 适配器,完全不走配置文件
func newTestCache() cache.Cache {
    c, err := memory.NewCache().NewCache("memory", `{"interval":1}`)
    if err != nil {
        panic(err)
    }
    return c
}

func TestTokenService_NormalPath(t *testing.T) {
    t.Parallel()
    svc := NewTokenService(newTestCache(), 3*time.Second)
    ctx := context.Background()

    assert.NoError(t, svc.SaveToken(ctx, "u123", "t999"))
    assert.True(t, svc.VerifyToken(ctx, "u123", "t999"))
    assert.False(t, svc.VerifyToken(ctx, "u123", "wrong"))
}

func TestTokenService_Expire(t *testing.T) {
    t.Parallel()
    svc := NewTokenService(newTestCache(), 1*time.Second)
    ctx := context.Background()

    _ = svc.SaveToken(ctx, "u_expire", "t888")
    time.Sleep(1200 * time.Millisecond)
    assert.False(t, svc.VerifyToken(ctx, "u_expire", "t888"))
}

func TestTokenService_ConcurrentSafe(t *testing.T) {
    t.Parallel()
    svc := NewTokenService(newTestCache(), 10*time.Second)
    ctx := context.Background()
    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func(idx int) {
            defer wg.Done()
            key := "concurrent"
            _ = svc.SaveToken(ctx, key, "same")
            _ = svc.VerifyToken(ctx, key, "same")
        }(i)
    }
    wg.Wait()
}

// 表驱动覆盖异常输入
func TestTokenService_TableDriven(t *testing.T) {
    t.Parallel()
    svc := NewTokenService(newTestCache(), 5*time.Second)
    ctx := context.Background()

    tests := []struct {
        name  string
        uid   string
        token string
        want  bool
    }{
        {"empty_uid", "", "tk", false},
        {"empty_token", "u", "", true}, // 允许空 token 保存
        {"binary_uid", "\x00\x01", "tk", true},
    }
    for _, tt := range tests {
        tt := tt
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel()
            _ = svc.SaveToken(ctx, tt.uid, tt.token)
            assert.Equal(t, tt.want, svc.VerifyToken(ctx, tt.uid, tt.token))
        })
    }
}

// 性能基准,给面试官量化数据
func BenchmarkTokenService_SaveAndVerify(b *testing.B) {
    svc := NewTokenService(newTestCache(), 10*time.Second)
    ctx := context.Background()
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            key := "bench"
            _ = svc.SaveToken(ctx, key, "v")
            _ = svc.VerifyToken(ctx, key, "v")
            i++
        }
    })
}

运行 go test -v -race -cover -bench=. 后,可得到:

  • 单测 100% 通过,-race 无 data race;
  • 覆盖率 100%(SaveToken、VerifyToken 两条路径全覆盖);
  • Benchmark 在 8C16G 笔记本上 QPS ≈ 60 万,延迟 p99 < 1 µs。

把这份报告甩给面试官,基本就稳了。

拓展思考

  1. 如何让单测也能验证“缓存穿透”逻辑?
    在 TokenService 里加一层“布隆过滤器”或“空对象缓存”,单测注入 memory 后,先查不存在 key,再查存在 key,验证过滤器是否生效。

  2. 如果生产环境用 redis 集群,单测如何模拟“网络抖动”?
    把 cache.Cache 再包一层 FaultableCache,内部用 github.com/facebookgo/clock 模拟超时,用 netem 或 toxiproxy 注入延迟,单测里验证重试、降级、熔断逻辑。

  3. 内存缓存的“过期回调”如何与业务事件总线打通?
    memory 适配器支持 ExpiredFunc,可在单测里把回调写入 chan string,主 goroutine 消费后断言事件内容,确保“缓存失效即发消息”的语义正确。

  4. 如何防止“单测通过、集成失败”?
    在 CI 流水线里再加一层“redis 容器集成测试”,用 github.com/ory/dockertest 拉起 redis,跑同一套表驱动用例,保证 memory 与 redis 行为一致,真正做到“左移质量”。