定义

Fake(伪对象) 在软件测试、尤其是单元测试和测试开发中,是一种常见的 Test Double(测试替身)。

Fake 是一种 “带有简化实现的替代对象”,它能部分模拟真实对象的行为,但不完全等价。

它通常 有实际逻辑、能跑起来,但只是 简化版 / 非生产级。

假设业务真正使用:MySQL 数据库、Redis 缓存、文件存储系统

这些在单元测试中启动非常慢,也很重。

于是你可以构造 Fake:FakeDB(伪数据库):用 内存 map 存储数据,不用启动真正的 MySQL;提供 find/add/update 接口;测试环境可运行、速度快。FakeCache(伪缓存):用 map 代替 Redis;实现 get/set 逻辑

它们可以运行,但不能用于生产,只适合测试。

样例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
type User struct {
ID int
Name string
}

type UserRepo interface {
GetUser(id int) (*User, error)
SaveUser(u *User) error
}

// Fake 实现
type FakeUserRepo struct {
data map[int]*User
}

func NewFakeUserRepo() *FakeUserRepo {
return &FakeUserRepo{
data: make(map[int]*User),
}
}

func (f *FakeUserRepo) GetUser(id int) (*User, error) {
if u, ok := f.data[id]; ok {
return u, nil
}
return nil, fmt.Errorf("not found")
}

func (f *FakeUserRepo) SaveUser(u *User) error {
f.data[u.ID] = u
return nil
}

现在,所有的单元测试都可以直接用:

1
2
repo := NewFakeUserRepo()
service := NewUserService(repo)

完全不需要真正的MySQL

Fake = 带简单实现的伪对象,用于替代真实组件,使测试更快更稳定。