TDD and Exceptions
Test-driven development (TDD) has a few simple rules. The definition and primary rule of TDD is that you must write tests first, before you write any production code. Think about what this means: You cannot write a lick of code unless you have specified a need for that code in a unit test.
Exceptions count as code! Exception throws are transfer of control statements, which means that they represent really interesting code. If you’re doing TDD, you must write test methods that allow you to drive out the code for managing exceptions. These exception test methods do three things:
- They document the kinds of problems that can occur when client code interacts with a class.
- They describe the context and conditions that can generate exceptions.
- They demonstrate how client code can recognize and respond to these exceptions.
The key point is that if you follow the rules of TDD, you’ll end up with empty catch blocks less frequently. TDD forces programmers to think about the kinds of problems that can occur with code, and it forces them to work proper error management into the design.