In Test Driven Development (TDD) you write code in incremental steps
- write a simple test describing the desired behavior of the implementation
- build out just enough of the implementation that the test can compile
- run the test and verify that it fails (the test runner generally shows red for this test)
- implement the desired behavior – just enough to pass the test
- re-run the test to verify that it passes (the test runner generally shows green for the test)
- optionally refactor the implementation
- verify that all tests for the implementation still pass
- repeat the process with the next desired behavior
This process is often described as red-green-refactor.
You will quickly reach the point where just knowing that a test failed is insufficient information to know what to do about it. One solution to this problem is to modify your process to red-diagnostics-green-refactor (a variation I picked up from Matt Hinze). In the diagnostics step you make sure the test failure message is meaningful. For example, don’t just assert that age is 6. Provide an error message that describes what it means e.g. “received incorrect age when calculating leap year birth date.”
To practice using tests to drive implementation you can search for the word kata and the name of the language you use to code e.g. kata c#. Kata is a Japanese word meaning “formal exercise”. Look for pages where someone has described a kata that you find interesting then break out your tools and see if you can do it using TDD. I find kata that also have an associated step-by-step implementation to be the most educational because I can compare my implementation and TDD process with theirs when I’m done.
A good c# example is James Newkirk’s Stack implementation kata.
If possible use ping-pong style coding in pairs:
- one person writes a test describing the behavior to be implemented
- the other implements the behavior
- swap roles and repeat until all desired behavior has been implemented
If the code should be written defensively consider using an aggressive ping-pong style once the required functionally has been implemented.
- one person writes a test to try to break the implementation or otherwise cause something unexpected to happen (e.g. null objects, negative values, dates &c out of range, sql injection, etc.)
- the other person fixes the problem
- swap roles and repeat
With experience you’ll get to where you can tell that a piece of code could not have been written the way it is if it had been written using TDD.
As you read more kata implementations you’ll also get exposure to the different styles, tools, and frameworks people use to structure their tests, prepare mock interactions with other objects, separate the test implementation details from their description, and reduce the ceremonial aspects of their code.
Write about your experiences so that others can learn from you.