// Stuart Reges // 4/3/10 // // This program tests stage 2 of the SortedIntList project. A testing method // is called from main to test different calls on the SortedIntList // constructors. The testing method halts execution if it encounters an error. // // The basic approach of the testing code is to use an ArrayList to // compute the correct answer and to continually compare the SortedIntList to // the ArrayList. The manipulations performed on the ArrayList are // highly inefficient (sorting after each individual add). We can live with // this kind of inefficiency in a testing program, but it should not be taken // as an example of good coding. import java.util.*; public class Test2 { public static final int TEST_SIZE = 25; // # of test numbers to pick public static final int MAX_INT = 10; // max for test numbers picked public static void main(String[] args) { System.out.println("Testing SortedIntList()"); SortedIntList list = new SortedIntList(); test(list, SortedIntList.DEFAULT_CAPACITY, false); System.out.println("Testing SortedIntList(" + TEST_SIZE + ")"); list = new SortedIntList(TEST_SIZE); test(list, TEST_SIZE, false); System.out.println("Testing SortedIntList(false)"); list = new SortedIntList(false); test(list, SortedIntList.DEFAULT_CAPACITY, false); System.out.println("Testing SortedIntList(true)"); list = new SortedIntList(true); test(list, SortedIntList.DEFAULT_CAPACITY, true); System.out.println("Testing SortedIntList(false, " + TEST_SIZE + ")"); list = new SortedIntList(false, TEST_SIZE); test(list, TEST_SIZE, false); System.out.println("Testing SortedIntList(true, " + TEST_SIZE + ")"); list = new SortedIntList(true, TEST_SIZE); test(list, TEST_SIZE, true); } // This method builds up a list of the given size, eliminating duplicates // if unique is true, and comparing that result against the SortedIntList // passed as a parameter. The SortedIntList should be initially empty. public static void test(SortedIntList list, int size, boolean unique) { List result = new ArrayList(); String history = ""; Random r = new Random(); for (int i = 0; i < size; i++) { int next = r.nextInt(MAX_INT); history += " " + next; result.add(next); Collections.sort(result); list.add(next); String correct; if (unique) { correct = new TreeSet(result).toString(); } else { correct = result.toString(); } String test = list.toString(); if (!correct.equals(test)) { System.out.println("error when adding these values to list:" + history); System.out.println("list should = " + correct); System.out.println("actual list = " + test); if (result.size() > 1) { System.out.println("was working properly prior to adding" + " last value of " + next); } System.exit(1); } } System.out.println(" Passed"); } }