Test-driven development (TDD) can be explained relatively easily. At the same time, TDD turns out to be a skill that can only be properly acquired by practicing it. This step-by-step guide aims to do exactly that: get you acquainted with TDD by applying its practices to a somewhat academic example. This academic example ensures that you won't be distracted by other challenges. These additional challenges can be addressed in other katas.
You will learn to:
- Effectively and strictly apply TDD, i.e. writing tests for each and every line of code.
- To use code coverage effectively (i.e. always reaching 100%).
- That TDD and BDD are in fact very closely related.
- To work in tiny increments.
- Experience the joy every time the tests are green (again)!
The idea of this first exercise is to leave the participant intentionally little to no room to deviate from the described steps. This means you may feel a bit "micro-managed" at times. The idea is to rub the right practices in this way. In subsequent exercises, more elbow room will be given step by step.
The example we will implement is based on an idea of Uncle Bob's lesson 4:
Figure 1: The user story used for this exercise.
According to Kent Beck again, let's first make a plan/TODO list of how to implement such a user story:
- Start with an empty stack
- Define pop on an empty stack
- Define push on an empty stack
- Define pop on a non-empty stack
- Define multiple pushes and pops
Figure 2: Implementing a stack with TDD, based on an idea of Uncle Bob's lesson 4.
When practicing TDD, you make a mind switch from writing tests to writing (executable) specifications. In other words, we specify the behaviour that we would like our system to exhibit. An RSpec-like syntax helps us to do so, and so we will work with an appropriate framework for each language, e.g. Mamba offers us such an equivalent for Python.