title: Issue Using Mockito's When Method
body: <p>I'm struggling trying to teach myself Mockito.</p>
  
  <p>Consider the following method, <em>hasInventory()</em>, which should not really run in my way of thinking, but get set up to return <em>true</em> or <em>false</em> as I squirrel-cage my test. Class <em>Warehouse</em> is my "mocked-dependency".</p>
  
  <pre><code>public class Warehouse implements IWarehouse
  {
    private Map&lt; String, Integer &gt;    inventory;
  
    public Warehouse()
    {
      this.inventory = new HashMap&lt; String, Integer &gt;();
    }
  
    public final boolean hasInventory( String itemname, int quantity )
        throws InventoryDoesNotExistException
    {
      if( inventory == null )
        throw new InventoryDoesNotExistException();
  
      if( !inventory.containsKey( itemname ) )
        return false;
  
      int current = ( inventory.containsKey( itemname ) ) ? inventory.get( itemname ) : 0;
  
      return( current &gt;= quantity );
    }
    ...
  </code></pre>
  
  <p>In the JUnit test code, the first <em>when()</em> throws an exception because it literally interprets the method call (executing it) and, <em>inventory</em> being nil (see above), <em>InventoryDoesNotExistException</em> is thrown. There are other methods in the mocked-dependency class too, like <em>add()</em> and <em>remove()</em>. </p>
  
  <pre><code>@RunWith( MockitoJUnitRunner.class )
  public class OrderInteractionTest
  {
    private static final String TALISKER = "Talisker";
    private Order   systemUnderTest  = null;
  
    @Mock
    private Warehouse   mockedDependency = null;
  
    @Before
    public void init()
    {
      //MockitoAnnotations.initMocks( this );
      //mockedDependency = mock( Warehouse.class );
      this.systemUnderTest  = new Order( TALISKER, 50 );
    }
  
    @Test  
    public void testFillingRemovesInventoryIfInStock()  
    {  
      try  
      {  
        doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).add( anyString(), anyInt() );  
        doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).remove( anyString(), anyInt() );  
        when( mockedDependency.hasInventory( anyString(), anyInt() ) ).thenReturn( true );  
        when( mockedDependency.getInventory( anyString() ) ).thenReturn( 50 );
  </code></pre>
  
  <p>As I understand it, by the <em>when()</em> method, I'm asking Mockito precisely not to call <em>hasInventory()</em>, but just to return <em>true</em> instead whenever it's called as I test the class ("systemUnderTest"). Can anyone help me get past this point (or get some sense into my brain)? </p>
  
  <p>I'm linking <em>mockito-all-1.8.5.jar</em> and JUnit 4. </p>
  
  <p>Copious thanks to all who read this. </p>
  
  <p>Russ</p>