本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://yu-jack.github.io/2020/10/05/unit-test-best-practice-part-4/
Summary
Jack Yu’s Part 4 of a unit test best practices series (in Traditional Chinese). Covers the 3A Pattern (Arrange-Act-Assert) and good unit test naming conventions, with examples in both C# and JavaScript (describe-it). Translated from/informed by “Unit Testing: Principles, Practices, and Patterns” (Vladimir Khorikov).
Jack Yu 單元測試最佳實踐系列第 4 部分(繁體中文)。涵蓋 3A 模式(Arrange-Act-Assert)和良好的單元測試命名規範,有 C# 和 JavaScript(describe-it)示例。譯自/基於《單元測試的藝術》(Vladimir Khorikov)。
Key Points
- 3A Pattern: Arrange (準備 — setup data, mocks, expected results), Act (行動 — typically ONE line calling the behavior under test), Assert (驗證 — verify outcome)
- Arrange: don’t expose implementation logic here (no
1+1for expected values, noif-elsein test code) - Act: should be exactly one line; multiple lines suggest either: hard to diagnose failures, or poor encapsulation in production code
- Assert: may have multiple assertions for Unit of Behavior tests (vs. single result for Unit of Code tests); assert outcomes, not implementation details (e.g., “login succeeded” not “hash was called”)
- Test naming guidelines (from Khorikov):
- No rigid naming rules
- Name as if describing a scenario to a domain expert (not a programmer)
- Separate words with underscores
- Naming evolution example:
IsDeliveryValid_InvalidDate_ReturnsFalse→Delivery_with_past_date_is_invalid - describe-it (JS): use nested describe-it with human-readable descriptions following the same guidelines; hierarchical grouping improves readability
Insights
The instruction “don’t expose implementation logic in Arrange” is subtle but important: if expectedResult = hashPassword(input) appears in Arrange, the test will break when you refactor the implementation even if the behavior is still correct. Tests should be behavioral contracts, not implementation mirrors. The “Act = one line” rule is a useful smell detector for overly complex production code. The naming evolution from IsDeliveryValid_InvalidDate_ReturnsFalse to Delivery_with_past_date_is_invalid nicely demonstrates how progressively more business-language names make tests self-documenting.
Connections
Raw Excerpt
如何寫出一個好的 Unit Test:在此範例中看到了 arrange, act 以及 assert, 這是著名的 3A pattern。不能暴露程式的實作邏輯在這裡。