Test-driven development (TDD)

TDD is the counterintuitive idea that developers will improve their code’s design and accuracy by writing the tests before writing the code. When adding new logic to a program, the TDD process starts by writing an automated test that describes code behavior that does not yet exist. A new logic is added to the program in a strict TDD process only in response to a failing test.

Code design guidance

Writing tests before code rather than after allows our tests to help guide our code’s design in small, incremental steps. Over time this creates a well-factored codebase that’s easy to change.

Test-driven development (TDD) process

Success with test-driven development starts with trusting the process. The classic process goes like this:

  1. Create a test. The test should be short and test for one thing in our code. The test should run automatically.

  2. Make sure that test fails. Verifying the test failure before writing code helps ensure that the test does what we expect.

  3. Write the most straightforward code that could make the test pass. Don’t worry about good code yet. Don’t look ahead. Sometimes, write just enough code to clear the current error.

  4. After the test passes, refactor to improve the code. Clean up duplication. Optimize. Create new abstractions. Refactoring is a key part of the design, so don’t skip this.

  5. Rerun the tests to ensure we haven’t changed any behavior.

Repeat until done. In theory, this will ensure that our code is always as simple as possible and is still completely covered by tests.

Get hands-on with 1200+ tech skills courses.