D
TestingMedium30 XP4 min read

How do you apply Test-Driven Development (TDD) in Flutter?

TL;DR: TDD: Red (write a failing test) → Green (write minimum code to pass) → Refactor (clean up). In Flutter: write unit tests for business logic first, then implement. For UI: start with widget test assertions, then build the widget. TDD produces smaller, more testable classes.

Full Answer

TDD flips the development order: instead of code → test, you write test → code. This forces you to think about the API before implementation, leading to more testable, focused classes.

TDD Cycle: Red → Green → Refactor

  • Red: Write a test that fails (the feature doesn't exist yet)
  • Green: Write the minimum code to make the test pass (no more, no less)
  • Refactor: Clean up code while keeping tests passing
  • Repeat: Add next test
🎯

TDD works best for business logic, use cases, and parsers. For complex UI, consider BDD (Behavior-Driven Development) with integration tests that describe user stories.

Code Examples

dartTDD for a use case: calculate quiz score
Output
// Step 1: RED  — test fails (class doesn't exist)
// Step 2: GREEN — test passes (minimum implementation)
// Step 3: RED  — new test fails (no edge case handling)
// Step 4: GREEN — fix edge case
// Step 5: REFACTOR — extract constants, improve names

Common Mistakes

  • Writing tests after code (TAD — Test After Development) — tests confirm existing behavior instead of driving design
  • Writing too many assertions in one test — violates 'one logical assertion per test' guideline

Interview Tip

💡

TDD is a discipline. Mention that in Flutter, TDD works best bottom-up: domain layer first (pure Dart, fast tests), then repository layer (mocks), then BLoC/Cubit (bloc_test), then widgets. This order mirrors the dependency graph.

#TDD#red-green-refactor#test-first#BDD