Integration 测试
验证那个模块工作正确地 together, catching wiring bugs 单元测试 miss.
你将学到
- 什么 integration 测试是 and bugs 它们 catch
- 如何 选择边界 for integration 测试
- Using 真实对比 fake dependencies intentionally
- Keeping integration 测试快 and deterministic
概念讲解
Beyond Unit Tests
Unit tests prove that each function works in isolation, but they cannot prove that the functions fit together. An integration test lets two or more real modules interact and asserts that the collaboration produces the right result. This is where you catch mismatched interfaces, wrong column names, broken serializers, and transaction boundaries — the bugs that appear only when the pieces meet.
Choosing Boundaries
The art of integration testing is choosing where to draw the boundary. A good boundary is a seam where one side is fast and reliable to run for real, and the other side is expensive or non-deterministic. For example, you might let your repository and an in-memory database run for real, but stub the external payment gateway. Test the seams that are most likely to break and cheapest to run.
Real vs Fake Dependencies
Use real dependencies for the parts you want to verify (your own modules, an in-memory or test database) and fakes for the parts you cannot control (third-party APIs, the clock, email delivery). The goal is maximum confidence for minimum cost. A test database that resets between tests gives you real SQL behavior without the slowness of a shared remote database.
Speed and Determinism
Integration tests are slower than unit tests, so keep the suite lean. Reset shared state before each test, run them in parallel when safe, and tag them so developers can run a fast subset locally and the full suite in CI. Never let an integration test depend on leftover data from a previous run — that creates order-dependent flakiness that is miserable to debug.
In Practice
A common pattern is to use an in-memory or test database that resets in a beforeEach hook, giving you real SQL behavior without the latency of a remote server. For external services you cannot run locally — a payment gateway, an email provider — stub the thin adapter that wraps them, and let your own modules interact for real beneath. Watch out for tests that grow slow because they wait on real I/O; if an integration test takes more than a few hundred milliseconds, investigate whether part of it can be pushed down to a unit test. Keep integration tests tagged separately so a developer can run only the fast unit suite during tight inner-loop coding and defer the integration suite to pre-commit or CI. This keeps the local feedback loop fast while preserving the wiring confidence integration tests provide.
示例代码
// Integration test: UserService + real InMemoryUserRepository
import { describe, it, expect, beforeEach } from "vitest";
import { UserService } from "./UserService";
import { InMemoryUserRepository } from "./UserRepository";
describe("UserService with repository", () => {
let repo: InMemoryUserRepository;
let service: UserService;
beforeEach(() => {
repo = new InMemoryUserRepository(); // real module, fresh state
service = new UserService(repo);
});
it("persists a created user and can look it up", async () => {
const created = await service.create({ name: "Grace", email: "[email protected]" });
const found = await service.findById(created.id);
expect(found?.email).toBe("[email protected]");
});
});
仓库是 真实 in-memory implementation, 所以测试练习真实 collaboration 之间 service and storage 不使用 touching 慢外部数据库.
动手试一试
- HTTP 请求 Tester
Probe 真实端点你的 integration 测试 call.
- JSON Diff
Spot wiring mismatches 你的 integration 测试 reveal.
常见错误
错误写法
Sharing 数据库跨越测试不使用 resetting 它
正确做法
Truncate or recreate 测试数据库 in beforeEach Hook 所以每个测试开始从 known, 空状态.
错误写法
Stubbing 每个 dependency 直到测试测试无 真实
正确做法
如果你 replace 所有 collaborators, 你有 单元测试. Let at 最少模块你 想要到 验证 interact for 真实.
练习 Integration 测试
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。