title: Unit testing Collection in Java
body: <p>I have a unit test that will allow me to iterate through a Collection object containing a list of vehicle. Upon each iteration, I want to check to see if the vehicle is an instance of automobile. So my code looks a bit like this:</p>
  
  <pre><code>public class VehicleChecker {
      protected boolean checkVehicles(Garage garage) {
          for (Vehicle vehicle : garage.getVehicles() {
              if (vehicle instanceof Automobile) return true;
          }
      }
  }
  </code></pre>
  
  <p>So I wrote my code accordingly:</p>
  
  <pre><code>@Mock private Garage mockGarage;
  @Mock private VehicleCollection mockVehicleCollection;
  @Mock private VehicleCollectionIterator mockVehicleCollectionIterator;
  @Mock private Vehicle mockVehicle;
  
  @Test
  public void testCheckVehicles() {
  
      VehicleChecker testObject = new vehicleChecker();
  
      when(mockGarage.getVehicles()).thenReturn(mockVehicleCollection);
      when(mockVehicleCollection.iterator()).thenReturn(mockVehicleCollectionIterator);
      when(mockVehicleCollectionIterator.hasNext()).thenReturn(true).thenReturn(false);
      when(mockVehicleCollectionIterator.next()).thenReturn(mockVehicle);
  
      boolean result = testObject.checkVehicles(mockGarage);
  
      verify(mockGarage).getVehicles();
  }
  </code></pre>
  
  <p>The problem occurs with the verify statement. Based on how it was written, the test should pass. When I step through the code, however, I the code just skips the for loop entirely. Why is that? Is there a difference in the way one iterates through a Collection as opposed to an ArrayList? If so, how do I properly mock that interaction?</p>