Java Reference
In-Depth Information
Maxim 3. Test 0, 1, and many. Because we are testing vowels, we decide to use
5 for “many” —one for each vowel. In other situations it might be the number of
items in a list, or the number of lines in a file, etc. Using this maxim, we gener-
ate the following tests cases:
numberOfVowels("") , 0
(the empty string)
numberOfVowels("bcd") , 0
(zero vowels, many letters)
numberOfVowels("a") , 1
(one vowel, one letter)
numberOfVowels("bad") , 1
( one vowel, many letters)
numberOfVowels("aeiou") , 5
all vowels, many letters)
numberOfVowels("facetious") , 5
(typical case)
There is another way to think of “many”: many occurrences of the same
vowel. When dealing with the first maxim, we wrote a test that had three e 's.
Maxim 4. Test null, beginning, middle, and end. Beginning and end are cov-
ered in the penultimate test from the previous maxim. Middle ? Yes, in several of
the cases, the vowels occur in the middle of the argument. There is one item left:
the parameter might be null . This interacts with the next maxim, and we discuss
it there.
Maxim 5. Verify the documentation. In investigating the previous maxim, we
found a problem with the documentation: it does not state what the result of the
call numberOfVowels ( null ) should be. Should the method return 0 ? Or throw
an Exception ? Whatever decision is made, the method specification needs to be
improved. Here we decide to disallow null and to let the code throw an excep-
tion: We add a second sentence to the method description to document this case:
/** = the number of vowels in s .
Throw a NullPointerException if s is null . */
public static int numberOfVowels(String s) {
return -1;
}
[It would be more appropriate to throw an IllegalArgumentException , but this
requires knowledge of the try-statement or throw-statement. See Sec. 10.4.1)
The test case in this case is the following:
numberOfVowels( null ) , an exception
Now here is something really neat: after spending 5-10 minutes writing test
cases, we have a thorough understanding of how the method behaves and have
improved the method specification, before we have written a single line of code .
14.1.3
A test driver
Remember the second maxim: test early and often . When testing a method, this
means that the method should be tested against all test cases when the method is
 
Search WWH ::




Custom Search