H
K
L
N
Q
Z

Test-Driven Development (TDD)

Test-driven development, often abbreviated as TDD, is the name given to the practice where tests are written before the actual software itself and form the code’s driving factor. This practice goes counter to the conventional method where developers write software first and test for it later.

How does test-driven development work?

We can split test-driven development into three phases, named red-green-refactor.

  • Write test cases for all expected functionality beforehand. These tests, called specs, will be the litmus test of whether the code works as expected. Try to be as thorough as possible concerning edge cases. These tests will fail as there is no code to test: red.
  • Write the most straightforward code that passes all the tests. It might not be the most optimal solution, but it must pass all the test cases. Things like hard-coding or poor big-O characteristics are acceptable. The tests are now passing: green.
  • Refactor code to optimize the implementation and remove code smells. Try to improve big-O characteristics by optimizing the algorithm. Keep running the tests after every change to ensure that none of the tests goes red. If any test fails, undo the change.

What are the best practices in test-driven development?

  • Write comprehensive test cases. Since the test cases are the requirements to be met, their exhaustiveness is crucial.
  • Avoid tests based on state or history. Always write tests that have a known starting state that is independent of other tests.
  • Since the internal implementation of a function might change, the test should only cover the external surface and not the implementation details.
  • Write atomic tests. Each test should cover one case only to determine the point of failure from the failing test itself.

Automate objective parts of code reviews

Automate objective parts of code reviews

Get started