TDD viết test trước code — quy trình Red-Green-Refactor: Red (viết test cho behavior mong muốn, test fail vì code chưa có), Green (viết minimum code đủ để test pass — không over-engineer), Refactor (cải thiện code structure, remove duplication trong khi tests vẫn pass).
- Lợi ích thực tế: buộc suy nghĩ về API/interface trước implementation — kết quả là better-designed, more testable code; coverage cao tự nhiên vì code chỉ được viết khi có test; dễ refactor vì test suite là safety net.
Ví dụ: test 'calculateTax(100, 0.1) should return 10' → implement calculateTax → refactor nếu cần.
TDD means writing tests before code — following the Red-Green-Refactor cycle: Red (write a test for the desired behavior; the test fails because the code does not exist yet), Green (write the minimum code needed to make the test pass — do not over-engineer), Refactor (improve code structure and remove duplication while tests continue to pass).
- Practical benefits: forces thinking about the API/interface before implementation — resulting in better-designed, more testable code; naturally achieves high coverage because code is only written when a test exists; easier to refactor because the test suite acts as a safety net.
- Example: test 'calculateTax(100, 0.1) should return 10' → implement calculateTax → refactor if needed.
- Micro-TDD cycles: each cycle takes 2-10 minutes, testing one small behavior at a time.
- TDD does not have to be rigidly 'test first' — many developers practice 'test alongside' (writing tests in parallel with code).
- When TDD is hard: legacy code that is not testable (needs refactoring first), UI-heavy code (E2E tests are difficult to TDD), exploratory code when the design is still unknown.
- Detroit vs London schools: Detroit (classic TDD, bottom-up, focuses on state verification, minimal mocking); London (mockist TDD, top-down with mocks for collaborators, verifies interactions).
- Practical advice: TDD is especially valuable for business logic, algorithms, and utilities; less valuable for simple CRUD and UI layout.