Java Reference
In-Depth Information
Using a try-statement . If you have not yet studied try-statements, skip this note. Below is an
advanced test that uses a try-statement to test for a null argument.
try {
numberOfVowels( null );
// If this point is reached there is a problem
System.out.println("Whoops, expected an exception.");
} catch (NullPointerException e) {
// If this point is reached, the method worked correctly,
// so this block is empty
Maxim 5. Verify the documentation.
As you test, ask yourself questions that you would not normally think of
while writing the code. Make sure the documentation answers those ques-
tions. (These are called design decisions. )
Example of creating test cases
Consider this method header and comment:
/** = the number of vowels in s */
public static int numberOfVowels(String s) {
return -1;
We have written the method body with a return statement so that the method
will compile. Such a method body, which does not do the right thing but is writ-
ten simply to allow the program to compile, is sometimes called a stub . After
compiling, we will begin writing the method body, but first we use the five max-
ims to generate test cases. Yes, we are going to generate the test cases before
writing the method! At the end, we show you how to put them together into a
method that you can use to easily test the method whenever you want.
Maxim 1. Test early and often. To test early, we need a test case. Below, we
show a test case, which consists of a typical call to numberOfVowels and the
answer we expect from it:
numberOfVowels("This sentence has vowels.") , 7
Maxim 2. Test only one thing at a time. Remember the three possible kinds of
bugs: incorrect value, incorrect change of data, and exception. Here, because
there is no outside data to corrupt, we focus on the first: the method may return
a wrong value. Later, as you test more complicated code, you might have sever-
al methods in a class. You will need to test how the methods interact, and this
maxim can be used to figure out how complicated to make your testing.
Search WWH ::

Custom Search