Skip to main content

Test-Driven Development (TDD)

Test-Driven Development (TDD) is a software development practice where developers write automated tests for a new feature before writing any of the code for that feature. This process follows a cycle of three steps: Red-Green-Refactor.

  1. Red: Write a small, failing test for a new piece of functionality.
  2. Green: Write just enough code to make the test pass.
  3. Refactor: Clean up and optimize the code, ensuring the test still passes.

This cycle helps ensure that every piece of code has a corresponding test, leading to more reliable, maintainable, and robust software.

Example: A developer is tasked with creating a new password validation feature. Following TDD, they would first write a test that checks if a password containing fewer than eight characters fails validation. This test would initially fail because the validation logic doesn't exist yet. The developer then writes the minimal amount of code needed to make that specific test pass. Once it passes, they clean up the code and repeat the cycle for the next requirement, like checking for a special character.