title: Mockito - Stubbing a method of an object that was returned by a mock object method
body: <p>Let's say I have an mock object, and I don't want to stub any of it's methods, but I want to stub a method of an object it returns. For example,</p>
  
  <pre><code>when(mockObject.method1()).thenReturn(returnValue)
  </code></pre>
  
  <p>is how it's normally done, but I'm looking for,</p>
  
  <pre><code>when(mockObject.method1().method2()).thenReturn(returnValue)
  </code></pre>
  
  <p>Is that possible? I get a NullPointerException if I do that. Currently I have stub the first method to return a mock object, and then using that returned mock object, stub the second method. However, these temporary mock objects are useless to me and after chaining many methods together, that results in a lot of useless mock objects.</p>
  
  <p>EDIT: Actually, it's possible that chaining works, but my objects are causing the NPE. This code (the first line) is causing a NPE:</p>
  
  <pre><code>when(graphDb.index().getNodeAutoIndexer()).thenReturn(nodeAutoIndexer);
  when(graphDb.index().getRelationshipAutoIndexer()).thenReturn(relAutoIndexer);
  </code></pre>
  
  <p>But this code works:</p>
  
  <pre><code>IndexManager indexManager = mock(IndexManager.class);
  when(graphDb.index()).thenReturn(indexManager);
  when(indexManager.getNodeAutoIndexer()).thenReturn(nodeAutoIndexer);
  when(graphDb.index().getRelationshipAutoIndexer()).thenReturn(relAutoIndexer);
  </code></pre>
  
  <p>So chaining didn't work for getNodeAutoIndexer() which returns an AutoIndexer object while it worked for getRelationshipAutoIndexer() which returns a RelationshipAutoIndexer. Both return values are mocked as follows:</p>
  
  <pre><code>nodeAutoIndexer = (AutoIndexer&lt;Node&gt;) mock(AutoIndexer.class);
  relAutoIndexer = mock(RelationshipAutoIndexer.class);
  </code></pre>
  
  <p>So what could be causing the problem?</p>