title: Mockito: how to stub void methods to run some code when called
body: <p>I want to stub a repository class to test another class (Holder class) that has a repository. The repository interface supports CRUD operations, and has many methods, but my unit test on the Holder class only needs to call two of them. The repository interface:</p>
  
  <pre><code>public interface IRepo {
      public void remove(String... sarr);
  
      public void add(String... sarr);
  
      //Lots of other methods I don't need now
  }
  </code></pre>
  
  <p><strong>I want to create a repository mock that can store instances, define logic for <code>add</code> and <code>remove</code> only, and also provide a means of checking what is stored on it after calling add and remove.</strong></p>
  
  <p>If I do:</p>
  
  <pre><code>IRepo repoMock = mock(IRepo.class);
  </code></pre>
  
  <p>Then I have a dumb object that does nothing on each method. That's OK, now I just need to define behaviour for add and remove.</p>
  
  <p>I could create a <code>Set&lt;String&gt;</code> and stub only those two methods to work on the set. Then I'd instantiate a Holder that has an IRepo, inject the partially stubbed mock, and after exercising the holder, check the set to verify it contains what it should.</p>
  
  <p>I've managed to partially stub a void method like <code>remove</code> using the deprecated method <code>stubVoid</code>:</p>
  
  <pre><code>Set&lt;String&gt; mySet = new HashSet&lt;&gt;();
  stubVoid(repoMock).toAnswer(new Answer&lt;Void&gt;() {
  
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
          Object[] args = invocation.getArguments();
          String[] stringsToDelete = (String[]) args[0];
          mySet.removeAll(Arrays.asList(stringsToDelete));
          return null;
      }
  }).on().remove(Matchers.&lt;String&gt;anyVararg());
  </code></pre>
  
  <p>But is deprecated, and it is not much better than creating a partial implementation for IRepo. Is there a better way?</p>
  
  <p>NOTE: Java 7 answers only please, this should run in Android.</p>