如何基于 Cache 接口编写单元测试并替换为 memory 适配器?
解读
在国内一线/二线互联网公司的 Go 后端面试中,Beego 的 cache 模块常被用来考察候选人对“接口抽象 + 依赖注入 + 单测隔离”的掌握程度。
面试官真正想确认的是:
- 你是否理解 Beego 的
cache.Cache接口,而非只会在配置文件里写adapter=memory。 - 你是否能把“外部依赖”变成“可注入的依赖”,从而让单测在毫秒级、无端口、无文件、无网络的环境下跑完。
- 你是否会利用
memory适配器“线程安全 + 自动过期”的特性,覆盖正常路径、异常路径、并发路径、过期路径四种场景。 - 你是否能写出“可维护”的单测:表驱动、子测试、并行、无全局状态、无
init()魔术。
如果候选人只能说出“把 beego.AppConfig 里的 adapter 改成 memory”,只能给 40 分;能把接口注入、并发安全、过期回调、benchmark 都讲清楚,才能拿到 90+。
知识点
-
Beego Cache 抽象层
- 核心接口:
cache.Cache(Get/Put/Delete/IsExist/Incr/Decr/StartAndGC)。 - 所有适配器(memory、redis、file、memcache)均实现该接口,因此业务代码面向接口编程即可。
- 核心接口:
-
依赖注入姿势
- 构造器注入:业务结构体里直接持有
cache.Cache字段,由main.go注入真实适配器,单测注入memory适配器。 - 配置隔离:单测目录下单独
app.conf,或完全不用配置文件,用代码显式NewCache("memory", …)。
- 构造器注入:业务结构体里直接持有
-
memory 适配器特点
- 基于
sync.RWMutex + map[string]*item,支持expire秒级过期。 - 启动成本为零,不需要端口、网络、文件句柄,单测并发跑 1 万用例也能毫秒级结束。
- 过期回调
ExpiredFunc可注入,用于验证“缓存击穿/雪崩”逻辑。
- 基于
-
单测编写规范(国内大厂 checklist)
- 必须子测试:
t.Run("caseName", func(t *testing.T){}),CI 失败时快速定位。 - 必须并行:
t.Parallel(),防止顺序跑拖慢 CI。 - 必须表驱动:覆盖“key 为空/超长/二进制”、“value 为 nil/大对象”、“并发安全”、“过期精准度”四类。
- 必须清零:每个用例结束后
cache.Delete()或重新NewCache,禁止全局 map 污染下一个用例。
- 必须子测试:
-
性能验证
- 附带
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。
把这份报告甩给面试官,基本就稳了。
拓展思考
-
如何让单测也能验证“缓存穿透”逻辑?
在TokenService里加一层“布隆过滤器”或“空对象缓存”,单测注入 memory 后,先查不存在 key,再查存在 key,验证过滤器是否生效。 -
如果生产环境用 redis 集群,单测如何模拟“网络抖动”?
把cache.Cache再包一层FaultableCache,内部用github.com/facebookgo/clock模拟超时,用netem或toxiproxy注入延迟,单测里验证重试、降级、熔断逻辑。 -
内存缓存的“过期回调”如何与业务事件总线打通?
memory 适配器支持ExpiredFunc,可在单测里把回调写入chan string,主 goroutine 消费后断言事件内容,确保“缓存失效即发消息”的语义正确。 -
如何防止“单测通过、集成失败”?
在 CI 流水线里再加一层“redis 容器集成测试”,用github.com/ory/dockertest拉起 redis,跑同一套表驱动用例,保证 memory 与 redis 行为一致,真正做到“左移质量”。