package lab.util; import static org.junit.Assert.*; import java.util.Date; import java.util.NoSuchElementException; import org.junit.Test; public class StackTest { @Test public void testConstructor() { Stack t = new Stack(); Node top = t.getTop(); assertNull("constructor should create an empty stack with no nodes", top); } @Test public void testIsEmpty() { Stack t = new Stack(); assertTrue("isEmpty should return true for an empty stack", t.isEmpty()); t.push("hi"); assertFalse("isEmpty should return false for a non-empty stack", t.isEmpty()); } @Test public void testSize() { Stack t = new Stack(); assertEquals("size should return 0 for an empty stack", 0, t.size()); for (int i = 1; i < 100; i++) { t.push("push " + i); assertEquals("size should return " + i + " for a stack with " + i + " elements", i, t.size()); } } @Test public void testPush() { Stack t = new Stack(); for (int i = 1001; i < 2001; i++) { Integer exp = i; t.push(exp); Integer got = t.getTop().getElement(); assertEquals("push failed to push the correct element to the top of the stack", exp, got); } } @Test public void testPopEmpty() { try { Stack t = new Stack(); t.pop(); fail("pop on an empty stack should have thrown an exception"); } catch (NoSuchElementException x) { // ok, pop should throw this exception } catch (Exception x) { fail("pop threw the wrong kind of exception"); } } @Test public void testPop() { Stack t = new Stack(); for (int i = 1001; i < 2001; i++) { Integer exp = i; t.push(exp); Integer got = t.pop(); assertEquals("pop failed to return the correct value", exp, got); t.push(got); } } @Test public void testPeek() { Stack t = new Stack(); for (int i = 1001; i < 2001; i++) { Integer exp = i; t.push(exp); Integer got = t.peek(); assertEquals("peek failed to return the correct value", exp, got); } } @Test public void testEqualsObject() { Date d = new Date(); Stack t = new Stack(); Stack u = new Stack(); assertFalse("t.equals(null) should return false", t.equals(null)); assertFalse("t.equals(d) should return false for a Stack t and a Date d", t.equals(d)); assertTrue("t.equals(u) should return true for empty stacks t and u", t.equals(u)); assertTrue("u.equals(t) should return true for empty stacks t and u", u.equals(t)); for (int i = 0; i < 10; i++) { t.push(i); } assertFalse("t.equals(u) should return false for different stacks t and u", t.equals(u)); assertFalse("u.equals(t) should return false for different stacks t and u", u.equals(t)); for (int i = 0; i < 10; i++) { u.push(i); } assertTrue("t.equals(u) should return true for same stacks t and u", t.equals(u)); assertTrue("u.equals(t) should return true for same stacks t and u", u.equals(t)); } }