next up previous
Next: Unit Testing and JUnit Up: Unit Testing in Java Previous: Tests Should be an

Write The Tests First

When interleaving the writing of tests with code, it's best to write the tests for each section of code before the corresponding code is written. By writing the tests before we write the code, you can help to solidify your understanding of what you want that code to do. You also know when we are done writing the code: when it passes all of the tests you've written. And if the tests don't capture all of our intended functionality, it's time to write more tests and repeat!

Another advantage of "test-first" programming is that the code you write will be designed from the very start to be easily testable, as you will never even write code until you've determined how it will be tested. Avoid the temptation to declare, for a particularly hard problem, "this code can't possibly be tested". Instead, ask yourself, "how could I design this code in such a way that I can test it?" In virtually all cases, you will find that if you approach the problem from this perspective, you will be able to devise a design that you can test quite naturally.


next up previous
Next: Unit Testing and JUnit Up: Unit Testing in Java Previous: Tests Should be an
Corky Cartwright 2004-02-05