Skip to content

测试双

一句话解释

测试双 是 umbrella term for 所有 replacement 对象 in 测试: mocks, stubs, spies, fakes, and dummies.

用大白话说

'测试双' 是 catch-所有 term for 任何 fake 对象那个 stands in for 真实 one 期间测试. name comes 从 'stunt 双' in movies — stand-in for 真实 actor.

There 是 five 主要类型的 测试 doubles:

  1. Dummy: placeholder 通过围绕但 从不 used. 只是 satisfies 参数需求.
  2. Stub: 返回 preset 值. Replaces 真实 behavior 使用 canned 响应.
  3. Spy: Wraps 真实函数, 记录 calls, and still 运行原始.
  4. Mock: pre-programmed 对象使用 expectations 关于如何它 应该是 called.
  5. Fake: 工作但 simplified implementation (e.g., in-memory 数据库相反的 真实 one).

In 练习, terms 是经常 used loosely — people say 'mock' 当它们平均值任何测试双. taxonomy comes 从 Gerard Meszaros' book 'xUnit 测试模式'.

示例

javascript
// Test doubles: stub, mock, spy, fake

// 1. STUB — replaces a function with a canned return value
const dbStub = { findUser: () => ({ id: 1, name: 'Alice' }) };

// 2. MOCK — stub + verifies the function was called
const mockSend = vi.fn();
notifyUser(mockSend, { id: 1 });
expect(mockSend).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }));

// 3. SPY — wraps real function, records calls without changing behavior
const spy = vi.spyOn(console, 'log');
doWork();
expect(spy).toHaveBeenCalledTimes(2);

// 4. FAKE — simplified working implementation
const fakeClock = { now: () => 1700000000000 }; // fixed time

四种测试替身:stub 返回预设值,mock 还验证是否被调用,spy 包装真实函数以记录调用,fake 是简化的可用实现(如内存数据库)。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表