Test-driven development (TDD)

The process where testing precedes development, which helps you catch edge cases early by forcing you to write a failing test for extreme inputs, boundary limits, or unexpected values (like null or empty data) before you write the actual code.

Published: 12:30 pm · 09 Jul 2024

Introduction

Diagram
Red-Green-Refactor loop
  • Red: Write a test for a specific edge case (it fails because the feature isn’t built yet).
  • Green: Write the bare minimum code to make that edge case pass.
  • Refactor: Clean up the code while keeping all normal and edge-case tests passing
Benefits of TDD
  • Better Code Quality: Forces simple, modular, and loosely-coupled design architectures.
  • Early Bug Detection: Catches edge cases and functional defects immediately during creation.
  • Living Documentation: Serves as a reliable, up-to-date specification of how the system behaves.
  • Fearless Refactoring: Provides a safety net when changing or scaling legacy codebases.
Common Pitfalls

Typical individual mistakes include:

  • Forgetting to run tests frequently
  • writing too many tests at once
  • writing tests that are too large or coarse-grained
  • writing overly trivial tests, for instance omitting assertions
  • writing tests for trivial code, for instance, accessors

Typical team pitfalls include:

  • Partial adoption – only a few developers on the team use TDD
  • poor maintenance of the test suite – most commonly leading to a test suite with a prohibitively long running time
  • the abandoned test suite (i.e. seldom or never run) – sometimes as a result of poor maintenance, sometimes as a result of team turnover

Reference