previous | start | next

Sample JUnit StackTest class

    1   
    2   import java.util.NoSuchElementException;
    3   import static org.junit.Assert.*;
    4   import org.junit.Before;
    5   import org.junit.Test;
    6   import org.junit.runner.*; // for JUnitCore.main
    7   
    8   /**
    9    * JUnit class to test the Stack class
   10    * 
   11    * @author Glenn Lancaster
   12    */
   13   public class StackTest
   14   {
   15     
   16     private Stack<String> s;
   17   
   18     @Before
   19     public void setup()
   20     {
   21       s = new Stack<String>();
   22     }
   23   
   24     @Test
   25     public void test1()
   26     {
   27       assertEquals(true, s.isEmpty());
   28       assertEquals(0, s.size());
   29       s.push("a");
   30       assertEquals(false, s.isEmpty());
   31       assertEquals("a", s.peek());
   32       assertEquals("a", s.pop());
   33       assertEquals(true, s.isEmpty());
   34     }
   35   
   36     @Test
   37     public void test2()
   38     {
   39       String[] x = {"a", "b", "c", "d"};
   40       for(int i = 0; i < x.length; i++) {
   41         s.push(x[i]);
   42         assertEquals(i + 1, s.size());
   43         assertEquals(x[i], s.peek());
   44       }
   45   
   46       for(int i = x.length - 1; i >= 0; i--) {
   47         assertEquals(x[i], s.pop());
   48       }
   49       assertEquals(true, s.isEmpty());
   50     }
   51   
   52     @Test(expected=NoSuchElementException.class)
   53     public void test3()
   54     {
   55       s.pop();
   56     }
   57   
   58     public static void main(String[] args)
   59     {
   60       JUnitCore.main("util.StackTest");
   61     }
   62   
   63   }


previous | start | next