Java Reference
In-Depth Information
Testing the Core Methods
14.15
Earlier, we realized that the add methods are fundamental to our class, so they are part of the core
group of methods that we implement and test first. The method toArray lets us see whether add
works correctly, so it too is in our core group. The constructor is also fundamental, and so is the
method clear , since the constructor calls it. Similarly, since add calls isEmpty and getNodeAt ,
they are among the core methods that we implement and test first. Lastly, we define the method
getLength as a check that the add methods correctly maintain the field numberOfEntries .
Although it is not really an essential method right now, its definition is simple and is the same as
for the array-based implementation that you saw in the previous chapter.
Now that we have implemented these core methods, we can test them. Since LList implements
ListInterface , however, we first must write stubs for the remaining methods in the interface. We
assume that we have completed that simple task.
Let's choose the add method that adds to the end of the list for our first tests. Listing 14-2
contains an example of a main method that we could use for this purpose. Notice how the
descriptive output makes it easier to see whether our implementation is correct. The method
displayList is the same as the one in Listing 12-2 of Chapter 12. Recall that this method calls
the methods getLength and getEntry .
LISTING 14-2
A main method that tests part of the implementation of the ADT
list
public static void main(String[] args)
{
System.out.println("Create an empty list.");
ListInterface<String > myList = new LList<String > ();
System.out.println("List should be empty; isEmpty returns" +
myList.isEmpty() + ".");
System.out.println("\nTesting add to end:");
myList.add("15");
myList.add("25");
myList.add("35");
myList.add("45");
System.out.println("List should contain 15 25 35 45.");
displayList(myList);
System.out.println("List should not be empty; isEmpty() returns" +
myList.isEmpty() + ".");
System.out.println("\nTesting clear():");
myList.clear();
System.out.println("List should be empty; isEmpty returns" +
myList.isEmpty() + ".");
} // end main
Output
Create an empty list.
List should be empty; isEmpty returns true.
Testing add to end:
List should contain 15 25 35 45.
 
Search WWH ::




Custom Search