Paths of Execution

Listing 2. In meeting the challenge of generating Iterator objects in different states that let you exercise all of the code's execution paths, you can freely choose the value of the REPEAT_COUNT constant.

import java.util.*;
import junit.framework.*;
public class SimpleIteratorTest extends TestCase
{
  private final static int REPEAT_COUNT = 10;

  public void testSimpleIterator() throws Throwable
  {
    Iterator testObject = new SimpleIterator();

      while (testObject.hasNext())
      {
        // Assert condition #3 for hasNext() == true:
        //
        for (int repeat = 0; repeat < REPEAT_COUNT; 
          repeat++)
          {
          assertTrue(testObject.hasNext());
          }

          // A violation of condition #1 will be 
          // automatically reported by JUnit: 
          //
          testObject.next();
      }

      // Assert condition #2:
      //
      String caught = null;
      try
      {
        testObject.next();
      }
      catch (Throwable throwable)
      {
        caught = throwable.getClass().getName();
      }
      assertEquals(
        NoSuchElementException.class.getName(), 
        caught);

      // Assert condition #4:
      //
      for (int repeat = 0; repeat < REPEAT_COUNT; 
        repeat++)
      {
        assertFalse(testObject.hasNext());
      }

      // Assert condition #5:
      //
      for (int repeat = 0; repeat < REPEAT_COUNT; 
        repeat++)
      {
        caught = null;
          try
          {
            testObject.next();
          }
          catch (Throwable throwable)
          {
            caught = throwable.getClass().getName();
          }
          assertEquals(
            NoSuchElementException.class.getName(), 
            caught);
      }
  }
}