Test-Driven Development (TDD): write test first; implement code to pass; refactor.
`apex // 1. Write failing test @isTest static void testCalculateScore() { Decimal score = ScoreCalculator.calculate(100); System.assertEquals(50, score); }
// 2. Implement to pass public class ScoreCalculator { public static Decimal calculate(Decimal input) { return input / 2; } }
// 3. Refactor; tests still pass. `
Behavior-Driven Development (BDD): describe behavior in natural language; auto-generated tests.
Given a Lead with Status = Working When user clicks Convert Lead Then Account, Contact, Opportunity created
Tools: Cucumber, Gauge.
TDD applied in Salesforce:
- Apex code: write test first; implement.
- Forces design clarity.
- Drives modularity.
- Most senior dev practice.
BDD applied in Salesforce:
- Better for collaboration with business.
- Tests double as documentation.
- Used in some agile teams.
- Tooling more limited than TDD.
Realistic adoption:
- TDD partial adoption common — write tests soon after code, not strictly first.
- BDD rare in pure form — Gherkin syntax used for documentation, not always automation.
Benefits:
- Cleaner code — easier to test.
- Confidence in changes — tests catch regressions.
- Documentation — tests describe expected behavior.
Common pitfalls:
- TDD without discipline — write code, then write tests retroactively.
- BDD without tooling — manual translation defeats purpose.
Senior insight: TDD/BDD are practices, not just tools. Discipline matters.
The senior framing: adopt elements of TDD/BDD where they add value; don't religiously apply.
