← 中文资源

简体中文版本

测试策略:单元、集成与端到端

按测试金字塔组织测试:快速单元测试、契约驱动的集成测试,以及少量高价值端到端测试。

阅读英文原文

引言

测试组合的目标是以最低成本获得最高信心。单元测试定位快,集成测试验证真实边界,端到端测试证明关键用户流程可用。三者不能互相替代。

测试金字塔

底层是大量快速、确定性的单元测试;中层是使用真实数据库、队列或 HTTP 边界的集成测试;顶层是少量关键路径的端到端测试。金字塔是反馈经济学的表达,不是硬性比例。

单元测试

测试纯逻辑、校验和边界条件,避免依赖真实时间、网络和随机性。用依赖注入和 fake 控制外部行为。一个单元测试失败应能直接指出哪个函数有问题。

集成与端到端

集成测试验证序列化、SQL、认证和事务等真实组合。端到端测试只覆盖登录、下单、支付等高风险流程,并使用稳定的选择器和等待策略。过度 mock 会制造虚假信心。

CI 与进阶

CI 应分层运行:快速测试在每次提交运行,慢测试在合并前运行。快照测试适合稳定输出,但不要用它替代行为断言。属性测试适合发现边界反例。用覆盖率找盲区,而不是追求数字。

代码示例

import { describe, it, expect } from "vitest";
import { formatPrice } from "./format";

describe("formatPrice", () => {
  it("formats USD with two decimals and the symbol", () => {
    expect(formatPrice(1234.5, "USD")).toBe("$1,234.50");
  });
  it("returns zero for negative amounts", () => {
    expect(formatPrice(-10, "USD")).toBe("$0.00");
  });
  it.each([[0, "USD", "$0.00"], [1, "JPY", "¥1"], [99.999, "EUR", "€100.00"]])(
    "formatPrice(%d, %s) === %s",
    (amount, currency, expected) => expect(formatPrice(amount, currency)).toBe(expected),
  );
});
import { vi } from "vitest";

it("returns cached price when the API fails", async () => {
  const api = { fetch: vi.fn().mockRejectedValue(new Error("network")) };
  const cache = { get: vi.fn().mockResolvedValue(42) };
  const service = new PriceService(api, cache);
  expect(await service.get("AAPL")).toBe(42);
  expect(api.fetch).toHaveBeenCalledOnce();
  expect(cache.get).toHaveBeenCalledWith("AAPL");
});
import { buildApp } from "./app";
import { createTestDb } from "./test/db";

describe("POST /users integration", () => {
  let app: ReturnType<typeof buildApp>;
  let db: Awaited<ReturnType<typeof createTestDb>>;

  beforeAll(async () => {
    db = await createTestDb();
    app = buildApp({ db });
  });
  afterAll(() => db.close());

  it("creates a user and returns 201 with the id", async () => {
    const res = await app.request("/users", { method: "POST", body: JSON.stringify({ email: "[email protected]" }) });
    expect(res.status).toBe(201);
    const { id } = await res.json();
    const found = await db.users.findById(id);
    expect(found?.email).toBe("[email protected]");
  });
});
import { test, expect } from "@playwright/test";

test("user can sign up and see the dashboard", async ({ page }) => {
  await page.goto("/signup");
  await page.getByLabel("Email").fill(`user-${Date.now()}@test.com`);
  await page.getByLabel("Password").fill("Sup3rSecret!");
  await page.getByRole("button", { name: "Create account" }).click();
  await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
  await expect(page).toHaveURL(/\/dashboard/);
});
// A focused snapshot of a generated config, not the whole object.
expect(pick(generated, "routes", "redirects")).toMatchInlineSnapshot();
// Inline snapshots put the expected value in the test file, where the diff is visible in code review.
import { fc, testProp } from "@fast-check/vitest";

testProp("sort is idempotent", [fc.array(fc.integer())], (arr) => {
  return JSON.stringify(sort(sort(arr))) === JSON.stringify(sort(arr));
});

testProp("parse and serialize round-trip", [fc.anything()], (value) => {
  return deepEqual(parse(serialize(value)), value);
});