测试 Doubles
理解 mocks, stubs, spies, and fakes — stand-ins 那个 keep 测试 isolated.
你将学到
- 什么测试双 是 and 为什么 isolation 需要它们
- four kinds: mocks, stubs, spies, and fakes
- 当到 use 每个 kind and trade-offs
- 如何测试 doubles prevent 测试从 touching 真实系统
概念讲解
The Problem of Dependencies
Real code calls other code: a service calls a repository, a component calls an API, a function reads the clock. If a unit test lets those calls reach the real systems, it becomes slow, non-deterministic, and tests more than one thing. A test double is a controlled stand-in for a real dependency, letting the test focus on the unit under test.
The Four Kinds
Gerard Meszaros classified test doubles into four kinds. A dummy is passed but never used (just to satisfy a parameter). A stub returns canned answers so the unit can proceed. A spy records how it was called (arguments, call count) while optionally delegating to the real implementation. A mock is a stub pre-programmed with expectations — the test fails if the expected calls do not happen. A fake is a working but simplified implementation, like an in-memory database.
Choosing the Right Double
Use a stub when you just need the dependency to return a value. Use a spy when you need to verify that your code called the dependency correctly (the right method, the right arguments). Use a mock when the interaction itself is the contract — for example, that saving a user calls exactly one email send. Use a fake when a simplified real implementation gives better confidence than canned values, such as an in-memory repository.
Trade-offs
Test doubles isolate and speed up tests, but over-mocking couples tests to implementation details: change a call site and many mocks break even though behavior is correct. Prefer fakes and stubs over mocks, and mock at architectural boundaries (external APIs, the filesystem) rather than between your own classes. The next lessons dive into each kind in detail.
In Practice
A good heuristic: if removing the double and using the real dependency would make the test slow or non-deterministic, the double is justified; if it would only make the test slightly slower but still correct, prefer the real thing. Fakes often give the best value — an in-memory repository behaves like the real one (it saves, finds, deletes) without the database cost, so your test exercises real logic rather than canned responses. Save mocks for the moments where the interaction itself is the contract: "placing 顺序发送精确地 one confirmation email." When you find yourself mocking five collaborators to test one method, step back — the method may have too many responsibilities, and the test is telling you to refactor. The doubles should serve the design, not fight it.
示例代码
import { describe, it, expect, vi } from "vitest";
// A stub: returns a fixed value so the unit can run
const stubRepo = { findById: vi.fn().mockResolvedValue({ id: 1, name: "Ada" }) };
// A spy: wraps a real function to observe calls
const realSend = (msg: string) => console.log(msg);
const spySend = vi.fn(realSend);
// A mock: asserts the interaction happened
describe("order service", () => {
it("sends exactly one confirmation email", async () => {
const service = new OrderService(stubRepo, spySend);
await service.place({ id: 1, total: 99 });
expect(spySend).toHaveBeenCalledTimes(1);
expect(spySend).toHaveBeenCalledWith(expect.stringContaining("confirmed"));
});
});
stubRepo feeds 数据, spySend observes email call, and mock expectation 验证 contract. 每个双 有单个, 清晰 purpose.
动手试一试
- JSON Formatter
Inspect canned 数据你的 stubs 返回.
- Code Diff
Compare recorded call 实参针对 expected ones.
常见错误
错误写法
Mocking 每个类 直到测试验证仅 mocks
正确做法
Mock at 边界 (I/O, 外部 services). Let 你的 own 领域对象 interact for 真实所以测试有 meaning.
错误写法
Confusing stub 使用 mock
正确做法
stub provides 答案; mock 验证 expectations. 如果你 做不 assert call 数量 or 实参, 它是 stub, 不 mock.
练习 测试 Doubles
6 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。