import junit.framework.*; import java.util.*; /** * Unit tests for SimpleArrayList. Recycled demo for CSE326b, 1/08 * * @author Hal Perkins * @version 1/17/08 */ public class SimpleArrayListTest extends TestCase { // instance variable and setup method used by several tests private SimpleArrayList testList; public void setUp() { testList = new SimpleArrayList(); testList.add("Bugs"); testList.add("Elmer"); testList.add("Tweety"); } // verify empty list created successfully public void testConstructor() { SimpleArrayList a = new SimpleArrayList(); assertEquals(0, a.size()); assertTrue(a.isEmpty()); } // check clear public void testClear() { testList.clear(); assertTrue(testList.isEmpty()); } // verify add increases the list size public void testAdd() { assertEquals(3, testList.size()); assertFalse(testList.isEmpty()); } // Verify that a SimpleArrayList contains // the number and values in the expected array // (used by several other testst to avoid redundant code; // not run directly by JUnit) private void checkEquals(Object[] expected, SimpleArrayList a) { assertEquals(expected.length, a.size()); for (int k = 0; k < expected.length; k++) { assertEquals(expected[k], a.get(k)); } } // Verify get return right values and checks positions public void testGet() { Object[] expected = {"Bugs", "Elmer", "Tweety"}; checkEquals(expected, testList); try { Object x = testList.get(-1); fail(); } catch (IndexOutOfBoundsException e) {} try { Object x = testList.get(testList.size()); fail(); } catch (IndexOutOfBoundsException e) {} } // Verify that set works properly public void testSet() { Object result = testList.set(0, "Mickey"); assertEquals("Bugs", result); Object[] expected = {"Mickey", "Elmer", "Tweety"}; checkEquals(expected, testList); result = testList.set(1, "Minnie"); assertEquals("Elmer", result); expected[1] = "Minnie"; checkEquals(expected, testList); result = testList.set(2, "Goofy"); assertEquals("Tweety", result); expected[2] = "Goofy"; checkEquals(expected, testList); try { Object x = testList.set(-1, "blah"); fail(); } catch (IndexOutOfBoundsException e) {} try { Object x = testList.set(testList.size(), "blah"); fail(); } catch (IndexOutOfBoundsException e) {} } // Verify search operations public void testIndexOf() { assertEquals(0, testList.indexOf("Bugs")); assertEquals(1, testList.indexOf("Elmer")); assertEquals(2, testList.indexOf("Tweety")); assertEquals(-1, testList.indexOf("C3PO")); } public void testContains() { assertTrue(testList.contains("Bugs")); assertTrue(testList.contains("Elmer")); assertTrue(testList.contains("Tweety")); assertFalse(testList.contains("R2D2")); } // verify remove operation // one case - in the middle; many others need checking public void testRemove1() { testList.remove(1); Object[] expected = {"Bugs", "Tweety"}; checkEquals(expected, testList); } }