In Object Oriented programming, it is conventional to do unit testing. That just means that each class or collection of classes is tested independently to make sure they are robust before trying to combine them into a program. Also, as we discussed before, the tests should be kept so that future maintanance can be carried out with confidence that things that used to work are not being broken.
We've already seen one way to arrange testing, using the assert
keyword. In one-class programs, we suggested using java to run the
program normally and java -ea to do testing. Now, main
is always used for testing. But we don't want to risk forgetting to add the
-ea flag, because then the tests wouldn't get run. So, we can add a
method which checks that assertions are enabled and reminds us to use
-ea if not. Here's the Book class with
main used for unit testing:
Book.java (version 4)
A couple of methods have been added to support testing. They have been made
static so they can be called from main, and they have been made
private. They could be put in some general purpose testing class where they
could be used from any class, instead of being repeated in every class that
does testing. The tests only use the public features of the class, not the
fields or private methods, to mimic the way the class is intended to be
used in the main program.
How much testing should you do? It has been said that it is impossible to test everything, but suicidal to test nothing. It is a matter of experience, but here are some rules of thumb:
Write a test to check for every bug you can foresee.
Every time you find a bug, write a test to demonstrate that you have fixed it, and to prevent it ever returning.
Before you write a class, write tests which illustrate every feature you expect it to have. Then you will know you have finished programming it when all the tests pass.