Video in progress

Junior 🧪 Testing

What is TDD, and how does the red-green-refactor cycle work?

TDD means first writing a failing test, then writing the simplest code that makes it pass, then cleaning the code up. Each step is small, and the code always grows protected by tests.

📖 Answer

The cycle has three steps:

  1. Red. You write a test for behavior that doesn't exist yet. It has to fail: if it doesn't, either the test is wrong or the feature already exists.
  2. Green. The minimal code that makes the test pass. It doesn't have to be pretty.
  3. Refactor. While the tests are green, you remove duplication and fix names.

A small example: PasswordPolicy. First the test "a password shorter than 8 characters is rejected" → return password.length() >= 8;. Then the test "a password without a digit is rejected" → you extend the condition. Every new rule starts with a test.

The benefit isn't only the number of tests. Because the test is written first, you see the class from the caller's side, and the API comes out nicer. If something is hard to test, the design is probably tangled too.

In practice not everyone does strict TDD. But it's very useful for bug fixing: first a test that reproduces the bug, then the fix.