Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Alice

StackExample


TestStack.java

import java.util.Iterator;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

/**
 * A simple test program for a stack
 * 
 * @author Chuck Cusack
 * @version 1.0, February 2008
 * @modified Feb 2013 (Updated to use JUnit)
 */
public class TestStack extends Object {
	@Test
	public void testArrayListStack() {
		StackInterface<String> stack = new ArrayListStack<String>();
		testThisStack(stack);
	}

	@Test
	public void testLinkedStack() {
		StackInterface<String> stack = new LinkedStack<String>();
		testThisStack(stack);
	}

	@Test
	public void testArrayStack() {
		StackInterface<String> stack = new ArrayStack<String>(4);
		testThisStack(stack);
	}

	public void testThisStack(StackInterface<String> stack) {

		// It should be empty to start.
		assertTrue(stack.isEmpty());

		// It should definitely not be full.
		assertFalse(stack.isFull());

		// Adding one element makes it neither full nor empty.
		stack.push("blah");
		assertFalse(stack.isEmpty());
		assertFalse(stack.isFull());

		// Add two more elements
		stack.push("foo");
		stack.push("ferzle");

		// Does the iterator work?
		Iterator<String> it = stack.iterator();
		String[] elements = { "ferzle", "foo", "blah" };
		int i = 0;
		while (it.hasNext()) {
			String s = it.next();
			assertEquals(elements[i], s);
			i++;
		}

		// Stack should not be full.
		assertFalse(stack.isFull());
		//
		assertEquals("ferzle", stack.peek());
		assertEquals("ferzle", stack.pop());
		assertEquals("foo", stack.pop());
		assertEquals("blah", stack.pop());
		assertTrue(stack.isEmpty());
	}
}