title: Mocking a Spy method with Mockito
body: <p>I am writing a unit test for a <code>FizzConfigurator</code> class that looks like:</p>
  
  <pre><code>public class FizzConfigurator {
      public void doFoo(String msg) {
          doWidget(msg, Config.ALWAYS);
      }
  
      public void doBar(String msg) {
          doWidget(msg, Config.NEVER);
      }
  
      public void doBuzz(String msg) {
          doWidget(msg, Config.SOMETIMES);
      }
  
      public void doWidget(String msg, Config cfg) {
          // Does a bunch of stuff and hits a database.
      }
  }
  </code></pre>
  
  <p>I'd like to write a simple unit test that stubs the <code>doWidget(String,Config)</code> method (so that it doesn't actually fire and hit the database), but that allows me to <em>verify</em> that calling <code>doBuzz(String)</code> ends up executing <code>doWidget</code>. Mockito seems like the right tool for the job here.</p>
  
  <pre><code>public class FizzConfiguratorTest {
      @Test
      public void callingDoBuzzAlsoCallsDoWidget() {
          FizzConfigurator fixture = Mockito.spy(new FizzConfigurator());
          Mockito.when(fixture.doWidget(Mockito.anyString(), Config.ALWAYS)).
              thenThrow(new RuntimeException());
  
          try {
              fixture.doBuzz("This should throw.");
  
              // We should never get here. Calling doBuzz should invoke our
              // stubbed doWidget, which throws an exception.
              Assert.fail();
          } catch(RuntimeException rte) {
              return; // Test passed.
          }
      }
  }
  </code></pre>
  
  <p>This <em>seems</em> like a good gameplan (to me at least). But when I actually go to code it up, I get the following compiler error on the 2nd line inside the test method (the <code>Mockito.when(...)</code> line:</p>
  
  <blockquote>
    <p>The method when(T) in the type Mockito is not applicable for the arguments (void)</p>
  </blockquote>
  
  <p>I see that Mockito can't mock a method that returns <code>void</code>. So I ask:</p>
  
  <ol>
  <li>Am I approaching this test setup correctly? Or is there a better, Mockito-recommended, way of testing that <code>doBuzz</code> calls <code>doWidget</code> under the hood? And</li>
  <li>What can I do about mocking/stubbing <code>doWidget</code> as it is the most critical method of my entire <code>FizzConfigurator</code> class?</li>
  </ol>