While his examples may be in Javascript, Jani Hartikainen has posted a guide that can help any developer get started with TDD - Test Driven Development - in their new or legacy applications.
What’s the hardest thing in test-driven development or unit testing in general? Writing tests! The syntax or the tools aren’t the problem – you can learn those enough to get started in 15 minutes. The problem is how to take some vague idea in your head about what you want to do, and turn it into something that verifies some function works… before you even wrote the damn thing!People tell you to use TDD. But how can you possibly write a test for something that doesn’t exist? I don’t even know what the function is going to do yet – or if I actually want two functions instead of one – and instead you want me to think of a test for it? Are you crazy?
How do all those people who tell you to use TDD do it? That’s the thing – test-driven development requires thinking of your code in a different way. And nobody ever tells you how to do that. Until now.
He then breaks down the process of how to turn a "vague idea" into something that can be effectively tested, noting that this change in thought process can sometimes be difficult. He then breaks it down into a set of five steps:
- Step 1: Decide the inputs and outputs
- Step 2: Choose function signature
- Step 3: Decide on one tiny aspect of the functionality
- Step 4: Implement test
- Step 5: Implement code
While the above may seem familiar to anyone that's read about TDD before, it's interesting to see how he explains each item with an emphasis on behavior not just the code required. He ends the post with a few more smaller suggestions to help you get on the road to TDD with the same emphasis on behavior rather than functionality.