Stubbing void methods with Mockito

I’ve been meaning to post something about this topic for a while, but it seems to have been slipping my mind. This post is targeted at those of you who use Mockito for your testing(Mockito is brilliant btw, and I applaud the folks over at Mockito for making this library!)

One thing that I got in the habit of was typing the when(mockClass.methodCall(eq(arg1))).thenCallRealMethod() etc, you’ll soon notice that if you’re trying to mock a void method, intellisense in any of your IDE’s will probably fail to allow you to select the methodCall method. There is an answer, and its way better than what was suggested in earlier versions. There is now a suite of doAnswer, doCallRealMethod, doNothing, doReturn(object), doThrow(exception) and the list goes on.

If you’re struggling to mock a void method, this is how you should go about it. Assuming you have a class that you would like to mock:


public class SampleClass {
   private String defaultValue = "default";

   public String getDefaultValue() {
    return defaultValue;
   }

   public void setDefaultValue(String defaultValue) {
    this.defaultValue = defaultValue;
   }
}

Here is a test class, mocking the behaviour of SampleClass, and setting up the test so that calls to the void method setDefaultValue are actually called, and subsequently verified with mockito.


public class SampleClassTest {

  private SampleClass sampleClass = mock(SampleClass.class);
  private String newDefaultValue = "Changed";

  @Test
  public void testOldWayOfVoidMethodMock(){

//   This is the old approach to attempting to mock void methods. I suggest
//   you avoid this in favour of the new method which is much
//   cleaner and more readable.

     stubVoid(this.sampleClass).toAnswer(new Answer() {
       public Object answer(InvocationOnMock invocation) throws Throwable {
         invocation.callRealMethod();
         return null;
       }
     }).on().setDefaultValue(eq(newDefaultValue));

     sampleClass.setDefaultValue(newDefaultValue);

     verify(sampleClass).setDefaultValue(newDefaultValue);
  }

  @Test
  public void testNewWayOfVoidMethodMock(){
//    Previously you would have been tempted to write something like
//    this to test void methods...
//    when(sampleClass.setDefaultValue(eq(newDefaultValue))).thenCallRealMethod();

//    However, this is how you should treat mocking void methods with
//    Mockito. Works with or without methods that require arguments
//    of course.
   doCallRealMethod().when(sampleClass).setDefaultValue(eq(newDefaultValue));

   sampleClass.setDefaultValue(newDefaultValue);

   verify(sampleClass).setDefaultValue(newDefaultValue);
 }
}

I’ve included two test methods to demonstrate the old suggested way, and the newly much more readable way. If you need more help then I suggest heading over to the mockito documentation which is pretty useful.

Advertisements