Trung BìnhTesting iconTesting

BDD (Behavior-Driven Development) là gì? Cú pháp Given-When-Then?

BDD là extension của TDD, focus vào behavior từ user/business perspective thay vì technical implementation.

  • Given-When-Then syntax: Given (context/preconditions — 'Given a user with $100 in account'), When (action — 'When they transfer $50'), Then (expected outcome — 'Then the balance should be $50 and recipient has $50').
  • Gherkin language: human-readable scenarios viết trong .feature files — Given/When/Then/And/But; được Cucumber parse và map đến step definitions trong code.
  • Lợi ích: common language giữa developers, QA, và business stakeholders; scenarios serve as living documentation; non-technical people có thể review và write scenarios.
  • Trong Jest/Vitest: BDD style với describe/it — it('should deduct amount from sender balance when transfer succeeds') đọc như specification.
  • Cucumber.js: feature files → step definitions (JS functions) → actual test code; overkill cho most projects trừ khi business stakeholders thực sự write scenarios.
  • Practical BDD: dùng Given-When-Then naming convention trong unit tests mà không cần Cucumber — captures intent, readable as docs.

Pitfall: BDD không phải chỉ về syntax — phải thực sự involve business trong defining behaviors, không chỉ wrap existing tests với Given/When/Then.

Xem toàn bộ Testing cùng filter theo level & chủ đề con.

Mở danh sách Testing