Java Reference
In-Depth Information
Testing the Core Methods
2.13
Getting ready. Now that we have defined the three core methods, we can test them. But what about
the other methods in BagInterface ? Since ArrayBag —as given in Listing 2-1—implements
BagInterface , Java's syntax checker will look for a definition of each method declared in this
interface. Should we wait until we complete their definitions to begin testing? Absolutely not! Test-
ing methods as you write them makes finding logical errors easier. However, instead of writing a
complete implementation of each method in BagInterface , we can provide incomplete definitions
of the methods we choose to temporarily ignore.
An incomplete definition of a method is called a stub . The stub needs only to keep the syntax
checker happy. For example, for each method that returns a value, you can avoid syntax errors by
adding a return statement that returns a dummy value. Methods that return a boolean value could
return true. Methods that return an object could return null . On the other hand, void methods can
simply have an empty body.
For instance, the method remove ultimately will return the removed entry, so its stub must con-
tain a return statement and could appear as follows:
public T remove()
{
return null ; // STUB
} // end remove
A stub for the void method clear could be
public void clear()
{
// STUB
} // end clear
Note that if you plan to call a stub within your test program, the stub should report that it was
invoked by displaying a message.
Programming Tip: Do not wait until you complete the implementation of an ADT
before testing it. By writing stubs, which are incomplete definitions of required methods, you
can begin testing early in the process.
2.14
A test program. Listing 2-2 shows a program to test the core methods add , isFull , and toArray of
the class ArrayBag 1 at this stage of its development. Initially, the main method creates an empty bag
by using the default constructor. Since the capacity of this bag is 25, it should not be full if you add
fewer than 25 entries to it. Thus, isFull should return false after these additions. The program's
descriptive output, in fact, indicates that the tested methods are correct.
Next in the main method, we consider a full bag by creating a bag whose capacity is seven and
then adding seven strings to it. This time, isFull should return true. Again, the program's output
shows that our methods are correct.
LISTING 2-2
A program that tests three core methods of the class ArrayBag
/**
A test of the methods add, toArray, and isFull, as defined
in the first draft of the class ArrayBag.
1.
Note that this version of the class ArrayBag is available online at the topic's website and is named ArrayBag1 .
 
 
Search WWH ::




Custom Search