Skip to content

Instantly share code, notes, and snippets.

@jcar787
Created September 27, 2014 20:52
Show Gist options
  • Save jcar787/3dfb711a5904b8ecde64 to your computer and use it in GitHub Desktop.
Save jcar787/3dfb711a5904b8ecde64 to your computer and use it in GitHub Desktop.
Unittest for the Deque class
import java.util.Iterator;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
public class DequeTest extends TestCase {
Deque<Integer> deque;
protected void setUp() throws Exception {
super.setUp();
deque = new Deque<Integer>();
}
protected void tearDown() throws Exception {
super.tearDown();
deque = null;
}
public void testIsEmpty() {
assertTrue(deque.isEmpty());
deque.addFirst(5);
assertFalse(deque.isEmpty());
deque.removeFirst();
assertTrue(deque.isEmpty());
deque.addLast(5);
assertFalse(deque.isEmpty());
deque.removeLast();
try {
deque.removeFirst();
fail("Should throw NoSuchElementException");
} catch (NoSuchElementException e) {
try {
deque.removeLast();
fail("Should throw NoSuchElementException");
} catch (NoSuchElementException nse) { }
}
}
public void testRemoveAtFirst() {
deque.addFirst(5);
deque.addFirst(15);
deque.addFirst(2);
assertEquals(2, (int) deque.removeFirst());
assertEquals(15, (int) deque.removeFirst());
assertEquals(5, (int) deque.removeFirst());
try {
deque.addFirst(null);
fail("Should throw NullPointerException");
}
catch (NullPointerException e) { }
}
public void testRemoveAtLast() {
deque.addLast(5);
deque.addLast(15);
deque.addLast(2);
assertEquals(2, (int) deque.removeLast());
assertEquals(15, (int) deque.removeLast());
assertEquals(5, (int) deque.removeLast());
try {
deque.addLast(null);
fail("Should throw NullPointerException");
}
catch (NullPointerException e) { }
}
public void testMixFirstAndLast() {
deque.addLast(5);
deque.addLast(15);
deque.addFirst(8);
deque.addFirst(33); // 33 - 8 - 5 - 15
assertEquals(15, (int) deque.removeLast());
assertEquals(33, (int) deque.removeFirst());
assertEquals(8, (int) deque.removeFirst());
assertEquals(5, (int) deque.removeLast());
assertTrue(deque.isEmpty());
}
public void testIteratorFor() {
deque.addLast(5);
deque.addLast(15);
deque.addLast(2);
deque.addLast(50);
deque.addLast(1);
deque.addLast(25);
int[] nums = { 5, 15, 2, 50, 1, 25 };
int i = 0;
for (Integer in : deque)
assertEquals(nums[i++], (int) in);
}
public void testIteratorWhile() {
deque.addLast(5);
deque.addLast(15);
deque.addLast(2);
deque.addLast(50);
deque.addLast(1);
deque.addLast(25);
int[] nums = { 5, 15, 2, 50, 1, 25 };
int i = 0;
Iterator<Integer> it = deque.iterator();
while (it.hasNext())
assertEquals(nums[i++], (int) it.next());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment