Java Reference
In-Depth Information
first written and then tested against all test cases whenever the method is
changed. Because testing is done frequently, the output from testing must be easy
to read. In fact, it is typical to print information only when a test case fails, so
that there is something to read only if there is a bug.
In Sec. 14.1.2, we created several test cases. Figure 14.1 contains a proce-
dure that exercises each test case. Such a method is often called a test driver .
It is assumed that this procedure is placed in the same class as function
numberOfVowels . Each test case (except the last) is wrapped in an if-statement,
which compares the expected answer with the answer given by the function.
Notice how we test whether the result is not what we expect. The last test case is
exercised using a call with argument null . Execution of this call should cause an
exception and abortion of execution.
Testing using JUnit
DrJava comes with a testing tool, JUnit, as do many IDEs. JUnit is the most com-
mon Java testing tool. The mechanics of using JUnit are explained in Sec. 2.4 of
Appendix I. Here, we show the use of JUnit to perform the tests described in Sec.
Figure 14.2 contains the same test cases as Fig. 14.1, this time to be tested
using JUnit. Thus, a class extends class TestCase . The class contains a public
/** Execute some tests */
public static void testNumberOfVowels() {
if (7 != numberOfVowels("This sentence has vowels.") )
{ System.out.println("A general test failed"); }
if (0 != numberOfVowels(""))
{ System.out.println("Empty case failed"); }
if (0 != numberOfVowels("bcd"))
{ System.out.println("A case without vowels failed"); }
if (1 != numberOfVowels("a"))
{ System.out.println("A case with one letter, a vowel, failed"); }
if (1 != numberOfVowels("bad"))
{ System.out.println("A case with mixture of vowels & letters failed"); }
if (5 != numberOfVowels("aeiou"))
{ System.out.println("A case with all vowels failed"); }
if (5 != numberOfVowels("facetious"))
{ System.out.println("A typical case failed"); }
numberOfVowels( null );
Figure 14.1:
A method for testing function numberOfVowels
Search WWH ::

Custom Search