Skip to content

单元测试

一句话解释

单元测试检查 one 小片段的 code — 典型地单个函数 — independently, 使用所有外部 dependencies replaced 通过 mocks or stubs.

用大白话说

单元测试是 如测试 one car 部分 in isolation. 相反的 测试整个 car, 你 take 只是 brake and 测试它 通过它自己. 你 don't 需要 engine, wheels, or transmission — 你 simulate 一切 brake 需要 and 测试仅 brake's logic.

In code, '单元' 是通常 one 函数 or 方法. 你 call 它使用特定输入 and 检查那个它 返回正确输出. 任何外部 things 它 depends on (数据库, network, other 函数) 是 replaced 使用 fake versions called mocks.

Unit 测试是 快 (milliseconds), numerous, and 应该是 基础的 你的测试 suite. 它们 give 你快速 feedback: 如果单元测试失败, 你 know 精确地哪个函数是 broken.

示例

javascript
// Function under test
function add(a, b) { return a + b; }

// Unit test
test('add returns sum of two numbers', () => {
  expect(add(2, 3)).toBe(5);
});

测试 calls 添加() directly and 检查返回值. 否 dependencies 到 mock.

工作原理

  1. Identify 函数 or 方法到 测试.
  2. 设置任何必需输入 (排列 phase).
  3. Call 函数使用那些输入 (Act phase).
  4. 检查输出 matches expectations (Assert phase).
  5. Mock 任何外部 dependencies 到 keep 测试 isolated.

常见混淆

  • 容易混淆的对象: Integration 测试

    关键区别: 单元测试检查 one 函数 in isolation; integration 测试检查多个组件工作 together.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表