Skip to content

Testing Strategies

Mở đầu

Code bạn thật sự "không vấn đề"? Mỗi lần sửa xong, click manual xem có hỏng — cách này OK khi project nhỏ, nhưng project lên vài chục nghìn dòng + team chục người = thảm hoạ.

Chương này: hiểu core strategy software testing, từ test pyramid đến TDD, build tư duy systematic quality assurance.

Bạn sẽ học:

ChươngNội dung
1Test pyramid
2Unit test practical
3TDD
4Strategy selection

0. Toàn cảnh: sao cần automated test?

Tưởng bạn là kỹ sư xây dựng. Mỗi sửa drawing không trèo từng tầng check structure — dùng automated detection system. Software test = "structural detection system" cho code.

Giá trị automated test

  • Regression protection: sửa A, auto check B, C, D có ảnh hưởng không
  • Refactor confidence: code có test → refactor an tâm
  • Living doc: test tốt = best manual
  • Fast feedback: vài giây biết code đúng/sai, không đợi deploy

1. Test pyramid

1.1 3 layer

Mike Cohn's test pyramid = classic strategy model. Mỗi loại test có proportion khác.

交互式测试金字塔 ── 点击每一层查看详情
🖥️E2E 测试
🔗集成测试
🧪单元测试
越往上:越慢、越贵、越接近用户越往下:越快、越多、越接近代码

1.2 Sao pyramid?

Reflect trade-off speed vs realism:

  • Bottom (unit): fast, most numerous, cheap, nhưng chỉ verify single piece
  • Middle (integration): medium, verify piece collaboration
  • Top (E2E): gần real user, nhưng slow, expensive maintain, brittle

Anti-pattern: ice-cream cone — E2E nhiều, unit ít. Test suite chậm, hay fail, maintain expensive.


2. Unit test practical

2.1 FIRST principles

PrincipleMeaningNote
FastNhanhms-level, dev willing run thường xuyên
IndependentĐộc lậpTest không depend nhau, run riêng được
RepeatableLặp đượcBất kỳ env kết quả giống
Self-validatingTự verifyPass/fail rõ, không cần judge
TimelyĐúng lúcViết test cùng (hoặc trước) code

2.2 AAA pattern

Mỗi test có 3-section structure:

javascript
test('Tính price với tax', () => {
  // Arrange
  const price = 100
  const taxRate = 0.13

  // Act
  const result = calculateTotalWithTax(price, taxRate)

  // Assert
  expect(result).toBe(113)
})

2.3 Test gì? Không test gì?

Should test:

  • Core business logic (price calc, permission, transform)
  • Edge case (null, zero, negative, huge)
  • Error path

Don't test:

  • 3rd-party lib internal
  • Simple getter/setter
  • Framework built-in (Vue reactivity)

3. TDD: Test-Driven Development

3.1 Red-Green-Refactor

TDD core = simple cycle: write test → write impl → refactor.

TDD 红绿重构循环 ── 点击"下一步"推进
🔴Red
🟢Green
🔵Refactor
第 1 步 / 5🔴 Red — 先写一个失败的测试
需求:实现 add(a, b) 函数。TDD 第一步不是写实现,而是先写测试。
add.test.js
test('add(1, 2) 应该返回 3', () => {
  expect(add(1, 2)).toBe(3)
})
❌ 测试失败 — add is not defined

3.2 3 rules

  1. Don't write production code, except to pass failing test
  2. Write just enough test code to fail (compile error counts as fail)
  3. Write just enough production code to pass test

3.3 Real value

Value không chỉ "test trước", mà force think interface design. Test trước = từ "user" view: function nhận param gì? Return gì? Tự nhiên hướng API tốt hơn.

TDD không silver bullet

TDD hợp logic-heavy (algorithm, business rule, data transform), nhưng UI layout, exploratory prototype → force TDD slow xuống. Key = hiểu ideology, apply linh hoạt.


4. Strategy selection

4.1 Project khác, focus khác

TypeFocusProportion
Tool/SDKUnit90% unit + 10% integration
API serviceIntegration30% unit + 60% integration + 10% E2E
Web appBalance50% unit + 30% integration + 20% E2E
MVP/prototypeCritical path E2EFew core test

4.2 Common tools

ToolTypeUse
VitestUnit/integrationVite first choice, Jest API compatible
JestUnit/integrationNode.js most popular
PlaywrightE2ECross-browser, Microsoft
CypressE2EDX tốt, debug dễ
Testing LibraryComponentUser-perspective UI test

5. AI assist testing

5.1 Gen unit test

Prompt:

Viết unit test cho function sau, Vitest framework:
1. AAA pattern
2. Cover normal + edge + error path
3. Mỗi test case có description rõ

[paste function]

5.2 Phát hiện edge case

Prompt:

Phân tích function, list mọi edge condition + extreme input:
null, zero, negative, huge, special char, concurrent.
Mỗi scenario: expected behavior + risk.

[paste function]

5.3 Requirement → test (TDD assist)

Prompt:

Implement shopping cart module:
- Add/delete/update qty
- Auto total price (kèm discount)
- Báo error khi out of stock

Theo TDD, viết test cases trước (no impl), Vitest, cover mọi core scenario.

AI caveat

AI gen test phải check assertion có nghĩa — tránh expect(true).toBe(true). Test tốt phải fail khi code sai.


6. Tổng kết

  1. Pyramid: bottom nhiều, top ít, balance speed + realism
  2. Unit test: FIRST + AAA, test core logic
  3. TDD: Red-Green-Refactor, test drive design
  4. Selection: theo project + stage

Insight cuối

Test không phải burden, mà accelerator. Short-term tốn time, long-term save vô số lần manual verify + regression debug + late-night emergency fix. Test tốt = tự tin "refactor được, test sẽ tell."

2026 cho VN dev

  • Modern stack 2026:
    • Vitest: chuẩn cho Vite project
    • Playwright: E2E dominant
    • MSW (Mock Service Worker): mock API
    • Testing Library: React/Vue component test
  • VN context:
    • Startup: Vitest đủ ban đầu
    • Enterprise: Jest legacy + Playwright cho E2E
  • AI testing:
    • GitHub Copilot: gen test tự động
    • Codium: AI-powered test generation
    • Diffblue (Java): AI gen test JUnit

Tài liệu